From 48daed36826189e5e6653a5b547a3491023563ea Mon Sep 17 00:00:00 2001 From: Jared Vititoe Date: Sat, 28 Nov 2026 23:43:21 -0500 Subject: [PATCH 1/4] CI: one pipeline that gates the deploy on every check and waits for prod to run it gandalf#55, part 1 (no server changes needed). - .gitea/workflows/ci.yml replaces lint.yml, test.yml and security.yml. Jobs: Lint (Python) with the dash check, Lint (JS), Test, Security, Scan (gitleaks over the full history, actionlint, shellcheck), Deploy and Notify. Deploy needs every check, so failing tests or a bandit or gitleaks finding no longer reach production. - Pinned: actions/checkout to a full SHA, job images to digests (Python 3.13 on Debian 13 like CT 157, Node 22 for eslint), Python tools in the new requirements-dev.txt, scanner downloads by SHA-256. No setup-python (the runner's shared tool cache broke Pulse twice). - Builds run on pull requests and on pushes to main only, plus a weekly run on main; concurrency queues deploys and never cancels one. - Deploy signs {"ref", "sha", "ts"} (unique per request), then waits up to 5 minutes until /health reports that commit for both processes, and only then tags deploy--. - /health reports `sha` (version.py reads .git at startup, no subprocess) and `monitor_sha` (the monitor writes it every cycle). Part 2 (server side): the pinned deploy script that refuses stale or replayed requests, deploys exactly that sha and rolls back. Co-Authored-By: Claude Opus 5.5 --- .gitea/workflows/ci.yml | 244 ++++++++++++++++++++++++++++++++++ .gitea/workflows/lint.yml | 101 -------------- .gitea/workflows/security.yml | 25 ---- .gitea/workflows/test.yml | 24 ---- .gitignore | 2 +- README.md | 34 +++-- app.py | 9 +- monitor.py | 3 + requirements-dev.txt | 5 + tests/test_app.py | 9 ++ tests/test_version.py | 48 +++++++ version.py | 39 ++++++ 12 files changed, 380 insertions(+), 163 deletions(-) create mode 100644 .gitea/workflows/ci.yml delete mode 100644 .gitea/workflows/lint.yml delete mode 100644 .gitea/workflows/security.yml delete mode 100644 .gitea/workflows/test.yml create mode 100644 requirements-dev.txt create mode 100644 tests/test_version.py create mode 100644 version.py diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml new file mode 100644 index 0000000..e70083d --- /dev/null +++ b/.gitea/workflows/ci.yml @@ -0,0 +1,244 @@ +name: CI + +# One pipeline (gandalf#55): every check must pass before main deploys, the deploy names the +# exact commit CI tested, and CI waits until production reports that commit as healthy. +# Actions are pinned to full commit SHAs and job images to digests (version in the comment). + +# Pushes build only main (which deploys); branches are built through their pull request, +# so nothing runs twice. Monday's run re-checks main against new advisories and rules. +on: + push: + branches: [main] + pull_request: + branches: ["**"] + schedule: + - cron: '0 6 * * 1' + +permissions: + contents: read + +concurrency: + group: ci-${{ github.ref }} + cancel-in-progress: ${{ github.ref != 'refs/heads/main' }} + +# Python comes from the job image, not actions/setup-python: the runner shares one tool +# cache between concurrent jobs, and parallel setup actions overwrote each other in Pulse. +# Python 3.13 on Debian 13 (trixie) matches production (CT 157). + +jobs: + lint-python: + name: Lint (Python) + runs-on: ubuntu-latest + timeout-minutes: 15 + container: python:3.13-trixie@sha256:f25cbd3f7c73c28bdcab476c93c93a2ec90970a8f5b8a7810533654207822390 + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + with: + persist-credentials: false + - name: Install pinned tools + run: python3 -m pip install -q --root-user-action=ignore -r requirements-dev.txt + - name: flake8 + run: flake8 . + - name: No em or en dashes (house style) + run: | + git config --global --add safe.directory "$GITHUB_WORKSPACE" + # Includes the vendored design system: it has been dash-free upstream since web_template#3. + if git grep -InP '[\x{2013}\x{2014}]|&[mn]dash;|\\u201[34]|̵[12];|ȁ[34];' \ + -- . ':!package-lock.json'; then + echo "::error::Em or en dashes found (listed above). Use a hyphen, colon, comma or 'to'." + exit 1 + fi + + lint-js: + name: Lint (JS) + runs-on: ubuntu-latest + timeout-minutes: 15 + container: node:22-bookworm@sha256:e13726ca604184d7a91fcacab1fc09eefd642dc28e79ac34e85540dd93b78cfb + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + with: + persist-credentials: false + - name: Install eslint (lockfile only) + run: npm ci --no-audit --no-fund + - name: eslint + run: npx eslint --ext .js static/ + + test: + name: Test + runs-on: ubuntu-latest + timeout-minutes: 20 + container: python:3.13-trixie@sha256:f25cbd3f7c73c28bdcab476c93c93a2ec90970a8f5b8a7810533654207822390 + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + with: + persist-credentials: false + - name: Install dependencies and pinned tools + run: python3 -m pip install -q --root-user-action=ignore -r requirements.txt -r requirements-dev.txt + - name: pytest with coverage + run: python3 -m pytest tests/ -q --cov=. --cov-report=term-missing --cov-config=.coveragerc + + security: + name: Security + runs-on: ubuntu-latest + timeout-minutes: 15 + container: python:3.13-trixie@sha256:f25cbd3f7c73c28bdcab476c93c93a2ec90970a8f5b8a7810533654207822390 + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + with: + persist-credentials: false + - name: Install pinned tools + run: python3 -m pip install -q --root-user-action=ignore -r requirements-dev.txt + - name: bandit + run: bandit -q -r . --exclude ./.git,./node_modules -ll + + scan: + name: Scan + runs-on: ubuntu-latest + timeout-minutes: 15 + container: python:3.13-trixie@sha256:f25cbd3f7c73c28bdcab476c93c93a2ec90970a8f5b8a7810533654207822390 + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + with: + persist-credentials: false + fetch-depth: 0 # gitleaks scans the whole history, not just this commit + - name: Install scanners (pinned versions, verified checksums) + run: | + cd /tmp + curl -fsSLo gitleaks.tgz https://github.com/gitleaks/gitleaks/releases/download/v8.30.1/gitleaks_8.30.1_linux_x64.tar.gz + echo "551f6fc83ea457d62a0d98237cbad105af8d557003051f41f3e7ca7b3f2470eb gitleaks.tgz" | sha256sum -c + curl -fsSLo actionlint.tgz https://github.com/rhysd/actionlint/releases/download/v1.7.12/actionlint_1.7.12_linux_amd64.tar.gz + echo "8aca8db96f1b94770f1b0d72b6dddcb1ebb8123cb3712530b08cc387b349a3d8 actionlint.tgz" | sha256sum -c + tar -xzf gitleaks.tgz -C /usr/local/bin gitleaks + tar -xzf actionlint.tgz -C /usr/local/bin actionlint + apt-get update -qq + DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends shellcheck >/dev/null + - name: Secrets in code and history (gitleaks) + run: | + git config --global --add safe.directory "$GITHUB_WORKSPACE" + gitleaks git --no-banner --redact --exit-code 1 . + - name: Workflow files (actionlint, with shellcheck on run scripts) + run: actionlint .gitea/workflows/*.yml + - name: Shell scripts (shellcheck) + run: git ls-files -z '*.sh' | xargs -0 -r shellcheck + + deploy: + name: Deploy + runs-on: ubuntu-latest + timeout-minutes: 15 + needs: [lint-python, lint-js, test, security, scan] + if: github.event_name == 'push' && github.ref == 'refs/heads/main' + container: python:3.13-trixie@sha256:f25cbd3f7c73c28bdcab476c93c93a2ec90970a8f5b8a7810533654207822390 + # Never run two deploys at once; queue instead of cancelling one mid-way. + concurrency: + group: deploy-production + cancel-in-progress: false + permissions: + contents: write # deploy tag + steps: + - name: Trigger the deploy webhook + env: + WEBHOOK_SECRET: ${{ secrets.WEBHOOK_SECRET }} + GIT_REF: ${{ github.ref }} + GIT_SHA: ${{ github.sha }} + run: | + # The sha and a timestamp make every signature unique. The server checks them once the + # pinned deploy script is installed (gandalf#55 part 2); until then it deploys origin/main. + python3 - <<'EOF' + import hashlib, hmac, json, os, time, urllib.request + body = json.dumps({'ref': os.environ['GIT_REF'], 'sha': os.environ['GIT_SHA'], + 'ts': int(time.time())}, separators=(',', ':')).encode() + sig = hmac.new(os.environ['WEBHOOK_SECRET'].encode(), body, hashlib.sha256).hexdigest() + req = urllib.request.Request('http://10.10.10.61:9000/hooks/gandalf-deploy', data=body, method='POST', + headers={'Content-Type': 'application/json', 'X-Gitea-Signature': sig}) + with urllib.request.urlopen(req, timeout=15) as resp: + print('Webhook:', resp.status, resp.read().decode()[:200]) + EOF + + - name: Verify production runs this commit + env: + GIT_SHA: ${{ github.sha }} + run: | + # The webhook returns at once; the deploy fetches, installs and restarts both services. + # Succeed only when /health reports this commit for the web app and the monitor, with a + # working database and a fresh monitor (up to 5 minutes). + python3 - <<'EOF' + import json, os, sys, time, urllib.request + want, last = os.environ['GIT_SHA'], 'no response' + for _ in range(60): + try: + with urllib.request.urlopen('http://10.10.10.61/health', timeout=5) as resp: + last = resp.read().decode() + except Exception as e: # 503 while the monitor catches up, or the restart itself + last = getattr(e, 'read', lambda: str(e).encode())().decode()[:300] + try: + body = json.loads(last) + except ValueError: + body = {} + if body.get('status') == 'ok' and body.get('sha') == want and body.get('monitor_sha') == want: + print(f'Production is healthy on {want}: {last}') + sys.exit(0) + time.sleep(5) + print(f'::error::Production never reported {want} as healthy (last /health: {last}). ' + 'See /var/log/gandalf-deploy.log on CT 157.') + sys.exit(1) + EOF + + - name: Tag the deployed commit + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + RUN_NUMBER: ${{ github.run_number }} + GIT_SHA: ${{ github.sha }} + REPO: ${{ github.repository }} + run: | + python3 - <<'EOF' + import json, os, sys, time, urllib.error, urllib.request + tag = time.strftime('deploy-%Y.%m.%d-', time.gmtime()) + os.environ['RUN_NUMBER'] + api = f"https://code.lotusguild.org/api/v1/repos/{os.environ['REPO']}/tags" + auth = {'Authorization': f"token {os.environ['GITHUB_TOKEN']}", 'Content-Type': 'application/json'} + body = json.dumps({'tag_name': tag, 'target': os.environ['GIT_SHA'], + 'message': 'Deployed to production'}).encode() + try: + urllib.request.urlopen(urllib.request.Request(api, data=body, headers=auth, method='POST'), timeout=15) + print(f"Tagged {os.environ['GIT_SHA']} as {tag}") + sys.exit(0) + except urllib.error.HTTPError as e: + code = e.code + # A rerun keeps its run number, so the tag can already exist: fine if it is this commit's + try: + with urllib.request.urlopen(urllib.request.Request(f'{api}/{tag}', headers=auth), timeout=15) as r: + existing = json.load(r).get('commit', {}).get('sha') + except Exception: + existing = None + if existing == os.environ['GIT_SHA']: + print(f'{tag} already marks this commit (a rerun)') + sys.exit(0) + print(f'::error::Could not tag {tag} (HTTP {code}; existing: {existing})') + sys.exit(1) + EOF + + notify: + name: Notify + runs-on: ubuntu-latest + timeout-minutes: 5 + needs: [lint-python, lint-js, test, security, scan, deploy] + # Any failure on main or in the weekly run, and every deploy outcome + if: >- + always() && ( + (failure() && (github.ref == 'refs/heads/main' || github.event_name == 'schedule')) || + needs.deploy.result == 'success' + ) + steps: + - name: Send Matrix alert + env: + MATRIX_WEBHOOK_URL: ${{ secrets.MATRIX_WEBHOOK_URL }} + REPO: ${{ github.repository }} + BRANCH: ${{ github.ref_name }} + RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} + RESULTS: "lint-python=${{ needs.lint-python.result }} lint-js=${{ needs.lint-js.result }} test=${{ needs.test.result }} security=${{ needs.security.result }} scan=${{ needs.scan.result }} deploy=${{ needs.deploy.result }}" + DEPLOYED: ${{ needs.deploy.result == 'success' }} + run: | + if [ -z "$MATRIX_WEBHOOK_URL" ] || [ "$MATRIX_WEBHOOK_URL" = "CONFIGURE_ME" ]; then exit 0; fi + if [ "$DEPLOYED" = "true" ]; then MSG="DEPLOYED: ${REPO} @ ${BRANCH} (${GITHUB_SHA:0:7})"; else MSG="CI FAILED: ${REPO} @ ${BRANCH} [${RESULTS}]"; fi + curl -sf -X POST "$MATRIX_WEBHOOK_URL" \ + -H "Content-Type: application/json" \ + -d "{\"text\":\"${MSG}: ${RUN_URL}\"}" diff --git a/.gitea/workflows/lint.yml b/.gitea/workflows/lint.yml deleted file mode 100644 index 3d60fc8..0000000 --- a/.gitea/workflows/lint.yml +++ /dev/null @@ -1,101 +0,0 @@ -name: Lint - -on: - push: - branches: ["**"] - pull_request: - branches: ["**"] - -jobs: - python-lint: - name: Python (flake8) - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v3 - - - name: Install Python and flake8 - run: | - apt-get update -qq - apt-get install -y -qq python3 python3-pip - pip3 install --break-system-packages flake8 - - - name: Run flake8 - run: flake8 . --exclude=__pycache__,.git - - js-lint: - name: JS (eslint) - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v3 - - - name: Install ESLint - run: npm install --save-dev eslint@8 - - - name: Run ESLint - run: npx eslint --ext .js static/ - - dashes: - name: No em or en dashes - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v3 - - - name: No em or en dashes (house style) - run: | - # Includes the vendored design system: it has been dash-free upstream since web_template#3. - if git grep -InP '[\x{2013}\x{2014}]|&[mn]dash;|\\u201[34]|̵[12];|ȁ[34];' \ - -- . ':!package-lock.json'; then - echo "::error::Em or en dashes found (listed above). Use a hyphen, colon, comma or 'to'." - exit 1 - fi - - notify-failure: - name: Notify on failure - runs-on: ubuntu-latest - needs: [python-lint, js-lint, dashes] - if: failure() && github.event_name == 'push' - steps: - - name: Send Matrix alert - env: - MATRIX_WEBHOOK_URL: ${{ secrets.MATRIX_WEBHOOK_URL }} - REPO: ${{ github.repository }} - BRANCH: ${{ github.ref_name }} - RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} - run: | - if [ -z "$MATRIX_WEBHOOK_URL" ] || [ "$MATRIX_WEBHOOK_URL" = "CONFIGURE_ME" ]; then exit 0; fi - curl -sf -X POST "$MATRIX_WEBHOOK_URL" \ - -H "Content-Type: application/json" \ - -d "{\"text\":\"CI FAILED: ${REPO} @ ${BRANCH}: ${RUN_URL}\"}" - - deploy: - name: Deploy - runs-on: ubuntu-latest - needs: [python-lint, js-lint, dashes] - if: github.event_name == 'push' && github.ref == 'refs/heads/main' - permissions: - contents: write - steps: - - name: Trigger webhook - env: - WEBHOOK_SECRET: ${{ secrets.WEBHOOK_SECRET }} - GIT_REF: ${{ github.ref }} - run: | - PAYLOAD="{\"ref\":\"${GIT_REF}\"}" - SIG=$(echo -n "$PAYLOAD" | openssl dgst -sha256 -hmac "$WEBHOOK_SECRET" | awk '{print $2}') - curl -sf --connect-timeout 10 \ - -X POST \ - -H "Content-Type: application/json" \ - -H "X-Gitea-Signature: ${SIG}" \ - -d "$PAYLOAD" \ - "http://10.10.10.61:9000/hooks/gandalf-deploy" - - - name: Tag deployed commit - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - run: | - TAG="deploy-$(date -u +%Y.%m.%d)-${{ github.run_number }}" - curl -sf -X POST \ - -H "Authorization: token $GITHUB_TOKEN" \ - -H "Content-Type: application/json" \ - -d "{\"tag_name\":\"${TAG}\",\"target\":\"${{ github.sha }}\",\"message\":\"Deployed to production\"}" \ - "https://code.lotusguild.org/api/v1/repos/${{ github.repository }}/tags" diff --git a/.gitea/workflows/security.yml b/.gitea/workflows/security.yml deleted file mode 100644 index eda4060..0000000 --- a/.gitea/workflows/security.yml +++ /dev/null @@ -1,25 +0,0 @@ -name: Security - -on: - push: - branches: ["**"] - pull_request: - branches: ["**"] - schedule: - - cron: '0 6 * * 1' - -jobs: - bandit: - name: Python Security (bandit) - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v3 - - - name: Install bandit - run: | - apt-get update -qq - apt-get install -y -qq python3 python3-pip - pip3 install --break-system-packages bandit - - - name: Run bandit - run: bandit -r . --exclude .git,__pycache__,node_modules -ll diff --git a/.gitea/workflows/test.yml b/.gitea/workflows/test.yml deleted file mode 100644 index fe83278..0000000 --- a/.gitea/workflows/test.yml +++ /dev/null @@ -1,24 +0,0 @@ -name: Test - -on: - push: - branches: ["**"] - pull_request: - branches: ["**"] - -jobs: - pytest: - name: Python Tests (pytest) - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v3 - - - name: Install Python and dependencies - run: | - apt-get update -qq - apt-get install -y -qq python3 python3-pip - pip3 install --break-system-packages pytest pytest-cov - pip3 install --break-system-packages -r requirements.txt --quiet - - - name: Run pytest with coverage - run: python3 -m pytest tests/ -v --cov=. --cov-report=term-missing --cov-config=.coveragerc diff --git a/.gitignore b/.gitignore index 9f72a9a..984ed9e 100644 --- a/.gitignore +++ b/.gitignore @@ -3,4 +3,4 @@ config.json config.json.* __pycache__/ *.pyc -node_modules/ \ No newline at end of file +node_modules/.coverage diff --git a/README.md b/README.md index 8f4987e..6421243 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,6 @@ # GANDALF (Global Advanced Network Detection And Link Facilitator) -[![Lint](https://code.lotusguild.org/LotusGuild/gandalf/actions/workflows/lint.yml/badge.svg)](https://code.lotusguild.org/LotusGuild/gandalf/actions?workflow=lint.yml) -[![Test](https://code.lotusguild.org/LotusGuild/gandalf/actions/workflows/test.yml/badge.svg)](https://code.lotusguild.org/LotusGuild/gandalf/actions?workflow=test.yml) -[![Security](https://code.lotusguild.org/LotusGuild/gandalf/actions/workflows/security.yml/badge.svg)](https://code.lotusguild.org/LotusGuild/gandalf/actions?workflow=security.yml) +[![CI](https://code.lotusguild.org/LotusGuild/gandalf/actions/workflows/ci.yml/badge.svg)](https://code.lotusguild.org/LotusGuild/gandalf/actions?workflow=ci.yml) > Because it shall not let problems pass. @@ -263,6 +261,9 @@ otherwise 503 with the failing check: `{"status": "degraded", "checks": {"db": " "monitor_age_s": 742}}`. The monitor counts as stalled after five missed polls (at least 10 minutes), so point an uptime monitor at it to catch a hung `gandalf-monitor`, not just a dead web app. +It also reports the commit each process runs: `sha` (the web app, read from `.git` at startup by +`version.py`) and `monitor_sha` (written by the monitor every cycle). CI's deploy waits for both. + ### Device pages (`/device/`) One page per host, switch, router, AP, PDU, or modem. Reach them from the search box on the dashboard (`/` focuses it), or from any device name. Search matches hostname, IP, MAC, model, type, @@ -1174,15 +1175,26 @@ Take LED colors from the model's quick start guide. See the comment at the top o ## CI / CD -| Workflow | Purpose | Triggers | -|---|---|---| -| `lint.yml` (python-lint) | flake8 on all `.py` files | Every push and PR | -| `lint.yml` (js-lint) | ESLint on `static/` | Every push and PR | -| `test.yml` | pytest: `diagnose.py`, `modem.py`, and `monitor.py` alert logic | Every push and PR | -| `security.yml` | bandit `-ll` (medium+ severity) | Every push, PR, and weekly Monday 6am | -| `deploy` job in `lint.yml` | Calls the `gandalf-deploy` webhook on CT157 (10.10.10.61) | Push to `main` only, after both lint jobs pass | +One pipeline, `.gitea/workflows/ci.yml` (gandalf#55). It runs on every pull request, on pushes to +`main`, and on Mondays at 06:00 UTC against `main`. -Branch protection is enabled on `main`: both lint jobs must pass before any PR can merge. +| Job | Runs | +|---|---| +| Lint (Python) | flake8, and the house-style check for em and en dashes | +| Lint (JS) | ESLint on `static/` (`npm ci` from the lockfile) | +| Test | pytest with coverage | +| Security | bandit `-ll` (medium and higher) | +| Scan | gitleaks over the full history, actionlint (with shellcheck) on the workflow, shellcheck on `*.sh` | +| Deploy | `main` only, after every job above passes | +| Notify | Matrix message on any failure on `main` or in the weekly run, and on every deploy | + +- **Pinned:** actions to full commit SHAs, job images to digests (Python 3.13 on Debian 13 like CT 157, + Node 22 for eslint), Python tools in `requirements-dev.txt`, and the scanner downloads by SHA-256. +- **Deploy:** signs `{"ref", "sha", "ts"}` with the webhook secret and calls `gandalf-deploy` on CT 157. + It then waits up to 5 minutes for `/health` to report that commit as `sha` and `monitor_sha` with + status ok, and only then tags it `deploy--`. Deploys queue; one is never cancelled mid-way. +- **Branch protection on `main`** requires every check job by its context name, e.g. + `CI / Lint (Python) (pull_request)`. Tests live in `tests/`: - `test_diagnose.py`: `DiagnosticsRunner` static methods (`build_ssh_command`, `parse_output`, diff --git a/app.py b/app.py index ebe8c2f..8c3b30d 100644 --- a/app.py +++ b/app.py @@ -31,6 +31,7 @@ import diagnose import kuma import modem as modem_api import topology +import version from monitor import PulseClient, UnifiClient, pause_smart_power, restore_smart_power logging.basicConfig( @@ -1813,8 +1814,14 @@ def health(): checks['monitor'] = 'error' overall = 'degraded' + # The commits the web app and the monitor run, so a deploy can wait for both (gandalf#55) + try: + monitor_sha = db.get_state('monitor_sha', '') or '' + except Exception: + monitor_sha = '' status_code = 200 if overall == 'ok' else 503 - return jsonify({'status': overall, 'service': 'gandalf', 'checks': checks}), status_code + return jsonify({'status': overall, 'service': 'gandalf', 'checks': checks, + 'sha': version.SHA, 'monitor_sha': monitor_sha}), status_code if __name__ == '__main__': diff --git a/monitor.py b/monitor.py index 8d2b68f..21503ea 100644 --- a/monitor.py +++ b/monitor.py @@ -31,6 +31,7 @@ import modem as modem_api import reboots import thor as thor_api import ticket_text +import version logging.basicConfig( @@ -2779,6 +2780,8 @@ class NetworkMonitor: while True: try: logger.info('Starting network check cycle') + # /health reports it, so a deploy can check the monitor restarted on the new commit too + db.set_state('monitor_sha', version.SHA) self._load_unused() # 1. Fetch interface states once: shared by snapshot and alert processing diff --git a/requirements-dev.txt b/requirements-dev.txt new file mode 100644 index 0000000..50ed5fd --- /dev/null +++ b/requirements-dev.txt @@ -0,0 +1,5 @@ +# Pinned tools for CI and local checks (gandalf#55). Runtime dependencies are in requirements.txt. +flake8==7.5.0 +bandit==1.9.4 +pytest==9.2.0 +pytest-cov==7.1.0 diff --git a/tests/test_app.py b/tests/test_app.py index 570995f..6b49323 100644 --- a/tests/test_app.py +++ b/tests/test_app.py @@ -473,6 +473,15 @@ class TestHealth: assert resp.status_code == 503 assert resp.get_json()['checks'] == {'db': 'ok', 'monitor': 'stale', 'monitor_age_s': 660} + def test_reports_the_running_commits(self, client): + from datetime import datetime, timezone + stamp = datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M:%S UTC') + state = {'last_check': stamp, 'monitor_sha': 'b' * 40} + gandalf.db.get_state.side_effect = lambda key, default=None: state.get(key, default) + with patch.object(gandalf.version, 'SHA', 'a' * 40): + body = client.get('/health').get_json() + assert body['sha'] == 'a' * 40 and body['monitor_sha'] == 'b' * 40 + def test_limit_follows_a_long_poll_interval(self, client): assert self._health(client, 1000, poll=300).status_code == 200 assert self._health(client, 1600, poll=300).status_code == 503 diff --git a/tests/test_version.py b/tests/test_version.py new file mode 100644 index 0000000..1760c4b --- /dev/null +++ b/tests/test_version.py @@ -0,0 +1,48 @@ +"""Tests for version.py: the running commit, read from .git without git itself (gandalf#55).""" +import os +import sys + +sys.path.insert(0, os.path.dirname(os.path.dirname(__file__))) + +import version # noqa: E402 + +A, B = 'a' * 40, 'b' * 40 + + +def _git(tmp_path, head, loose=None, packed=None): + g = tmp_path / '.git' + g.mkdir() + (g / 'HEAD').write_text(head + '\n') + if loose: + ref, sha = loose + p = g.joinpath(*ref.split('/')) + p.parent.mkdir(parents=True) + p.write_text(sha + '\n') + if packed: + (g / 'packed-refs').write_text('# pack-refs with: peeled fully-peeled sorted\n' + packed) + return str(tmp_path) + + +def test_detached_head_is_the_sha(tmp_path): + assert version.running_sha(_git(tmp_path, A)) == A + + +def test_branch_with_a_loose_ref(tmp_path): + assert version.running_sha(_git(tmp_path, 'ref: refs/heads/main', loose=('refs/heads/main', B))) == B + + +def test_branch_in_packed_refs(tmp_path): + packed = f'{A} refs/heads/other\n{B} refs/heads/main\n^{A}\n' + assert version.running_sha(_git(tmp_path, 'ref: refs/heads/main', packed=packed)) == B + + +def test_anything_unreadable_is_empty(tmp_path): + assert version.running_sha(str(tmp_path)) == '' # no .git + assert version.running_sha(_git(tmp_path, 'garbage')) == '' + other = tmp_path / 'y' + other.mkdir() + assert version.running_sha(_git(other, 'ref: refs/heads/gone')) == '' # ref missing + + +def test_this_checkout_reports_a_sha(): + assert version.SHA == '' or len(version.SHA) == 40 diff --git a/version.py b/version.py new file mode 100644 index 0000000..6099619 --- /dev/null +++ b/version.py @@ -0,0 +1,39 @@ +"""The git commit this process is running, read once at startup (gandalf#55). + +/health reports it so CI can wait until production runs the commit it tested. Read straight +from .git (no subprocess): a detached HEAD holds the sha itself; a branch HEAD points at a +loose ref or a line in packed-refs. Anything unreadable gives '' rather than an error. +""" +import os +import re + +_SHA = re.compile(r'^[0-9a-f]{40}$') + + +def running_sha(root: str = '') -> str: + """The 40-character commit sha checked out in *root* (default: this file's folder), or ''.""" + git = os.path.join(root or os.path.dirname(os.path.abspath(__file__)), '.git') + try: + with open(os.path.join(git, 'HEAD')) as f: + head = f.read().strip() + if _SHA.match(head): + return head + if not head.startswith('ref: '): + return '' + ref = head[5:].strip() + loose = os.path.join(git, *ref.split('/')) + if os.path.isfile(loose): + with open(loose) as f: + sha = f.read().strip() + return sha if _SHA.match(sha) else '' + with open(os.path.join(git, 'packed-refs')) as f: + for line in f: + parts = line.split() + if len(parts) == 2 and parts[1] == ref and _SHA.match(parts[0]): + return parts[0] + except OSError: + pass + return '' + + +SHA = running_sha() -- 2.47.3 From 58e4528eb59818d054819acbce4ef6c2b04af647 Mon Sep 17 00:00:00 2001 From: Jared Vititoe Date: Sat, 28 Nov 2026 23:43:29 -0500 Subject: [PATCH 2/4] gitignore: keep node_modules/ and .coverage on separate lines Co-Authored-By: Claude Opus 5.5 --- .gitignore | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index 984ed9e..f6e4a24 100644 --- a/.gitignore +++ b/.gitignore @@ -3,4 +3,5 @@ config.json config.json.* __pycache__/ *.pyc -node_modules/.coverage +node_modules/ +.coverage -- 2.47.3 From 77a5791bbfadd96066a655edcda4799d84e13c98 Mon Sep 17 00:00:00 2001 From: Jared Vititoe Date: Sat, 28 Nov 2026 23:52:16 -0500 Subject: [PATCH 3/4] CI: install Node before checkout in the Python jobs The runner (act) runs JavaScript actions such as actions/checkout inside the job container, and python:3.13-trixie has no node, so checkout failed with 'exec: node: executable file not found'. Debian's nodejs (20.x) is enough for checkout v4 and keeps the job image matching production. Co-Authored-By: Claude Opus 5.5 --- .gitea/workflows/ci.yml | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml index e70083d..6f2cec8 100644 --- a/.gitea/workflows/ci.yml +++ b/.gitea/workflows/ci.yml @@ -32,6 +32,9 @@ jobs: timeout-minutes: 15 container: python:3.13-trixie@sha256:f25cbd3f7c73c28bdcab476c93c93a2ec90970a8f5b8a7810533654207822390 steps: + - name: Node for the checkout action + # The runner (act) runs JS actions inside the job container, and the Python image has no Node + run: apt-get update -qq && DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends nodejs >/dev/null - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 with: persist-credentials: false @@ -69,6 +72,9 @@ jobs: timeout-minutes: 20 container: python:3.13-trixie@sha256:f25cbd3f7c73c28bdcab476c93c93a2ec90970a8f5b8a7810533654207822390 steps: + - name: Node for the checkout action + # The runner (act) runs JS actions inside the job container, and the Python image has no Node + run: apt-get update -qq && DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends nodejs >/dev/null - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 with: persist-credentials: false @@ -83,6 +89,9 @@ jobs: timeout-minutes: 15 container: python:3.13-trixie@sha256:f25cbd3f7c73c28bdcab476c93c93a2ec90970a8f5b8a7810533654207822390 steps: + - name: Node for the checkout action + # The runner (act) runs JS actions inside the job container, and the Python image has no Node + run: apt-get update -qq && DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends nodejs >/dev/null - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 with: persist-credentials: false @@ -97,6 +106,9 @@ jobs: timeout-minutes: 15 container: python:3.13-trixie@sha256:f25cbd3f7c73c28bdcab476c93c93a2ec90970a8f5b8a7810533654207822390 steps: + - name: Node for the checkout action + # The runner (act) runs JS actions inside the job container, and the Python image has no Node + run: apt-get update -qq && DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends nodejs >/dev/null - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 with: persist-credentials: false @@ -110,7 +122,6 @@ jobs: echo "8aca8db96f1b94770f1b0d72b6dddcb1ebb8123cb3712530b08cc387b349a3d8 actionlint.tgz" | sha256sum -c tar -xzf gitleaks.tgz -C /usr/local/bin gitleaks tar -xzf actionlint.tgz -C /usr/local/bin actionlint - apt-get update -qq DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends shellcheck >/dev/null - name: Secrets in code and history (gitleaks) run: | -- 2.47.3 From 8a23fe0922841ce57a453663eea0c3943e5e067e Mon Sep 17 00:00:00 2001 From: Jared Vititoe Date: Sat, 28 Nov 2026 23:54:39 -0500 Subject: [PATCH 4/4] monitor: space after a comma in an f-string (flake8 E231 on Python 3.13) Python 3.12+ tokenizes f-strings, so pycodestyle now checks inside them. CI runs flake8 on production's Python 3.13; the old CI and local checks ran an older Python and never saw it. Co-Authored-By: Claude Opus 5.5 --- monitor.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/monitor.py b/monitor.py index 21503ea..f6ba5c2 100644 --- a/monitor.py +++ b/monitor.py @@ -1870,7 +1870,7 @@ class NetworkMonitor: event_id, is_new, consec, ticket_id = db.upsert_event( 'unifi_device_offline', 'critical', 'unifi', name, d.get('type', ''), - f'UniFi {name} ({d.get("ip","")}) offline ({_now_utc()})', + f'UniFi {name} ({d.get("ip", "")}) offline ({_now_utc()})', ) if not sup and consec >= self.unifi_fail_thresh and not ticket_id: self._ticket_unifi(event_id, d) -- 2.47.3