diff --git a/.env.example b/.env.example index ac0a880..f2d5947 100644 --- a/.env.example +++ b/.env.example @@ -21,6 +21,9 @@ DEMO_PASSWORD=demo # Max size of imported files, in MB MAX_UPLOAD_MB=10 +# Token a monitor sends to /ops/metrics (counts only). Unset: the endpoint answers 404. +# OPS_METRICS_TOKEN= + # Logging LOG_LEVEL=DEBUG diff --git a/CHANGELOG.md b/CHANGELOG.md index 49abb29..a21f471 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Added +- `/health` for a monitor: public, answers `ok` and the running commit, or 503 when the database does not answer. +- `/ops/metrics`: counts for a monitor (days logged in the last week, worked and absences, days logged in total, users), with `Authorization: Bearer `. Without `OPS_METRICS_TOKEN` it answers 404. Never hours, dates or notes. + ## [2.1.0] - 2026-10-04 ### Added diff --git a/README.md b/README.md index 7f315d5..545c78d 100644 --- a/README.md +++ b/README.md @@ -120,6 +120,7 @@ Settings are read from the environment or from `.env`. The most relevant ones: | `DEMO_MODE` | `false` | Show the demo credentials on the login page. | | `DEMO_USERNAME` / `DEMO_PASSWORD` | `demo` / `demo` | Demo credentials (also used by `flask seed demo`). | | `MAX_UPLOAD_MB` | `10` | Maximum size of imported files. | +| `OPS_METRICS_TOKEN` | unset | Bearer token for `/ops/metrics` (days logged in the week and in total, users: counts only). Unset, the endpoint answers 404. `/health` is always public. | The Docker image also reads `SEED_DEMO` (load sample data on start) and `GUNICORN_WORKERS`. See [`.env.example`](.env.example) for the full list. diff --git a/app/__init__.py b/app/__init__.py index 3e1a6e9..1137469 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -11,6 +11,7 @@ from app.routes.main import main from app.routes.manual_entry import manual_entry from app.routes.monthly_log import monthly_log_bp +from app.routes.ops import ops_bp from app.routes.settings import settings_bp from app.routes.time_log import time_log from app.routes.time_summary import time_summary @@ -34,6 +35,7 @@ def create_app(config_object): app.register_blueprint(monthly_log_bp) app.register_blueprint(settings_bp) app.register_blueprint(api_bp) + app.register_blueprint(ops_bp) from app.routes.import_log import import_log_bp diff --git a/app/auth.py b/app/auth.py index 61a3dff..9822063 100644 --- a/app/auth.py +++ b/app/auth.py @@ -40,7 +40,14 @@ auth_bp = Blueprint("auth", __name__) # Endpoints reachable without a session. -PUBLIC_ENDPOINTS = {"auth.login", "static", "i18n.set_language"} +# /ops/metrics checks its own token (app/routes/ops.py). +PUBLIC_ENDPOINTS = { + "auth.login", + "static", + "i18n.set_language", + "ops.health", + "ops.metrics", +} # Failed login attempts per client IP, kept in memory (single process is enough # for a self-hosted single-user app). diff --git a/app/config/config.py b/app/config/config.py index fcabefc..303a5de 100644 --- a/app/config/config.py +++ b/app/config/config.py @@ -40,6 +40,10 @@ class Config: DEMO_USERNAME = os.getenv("DEMO_USERNAME", "demo") DEMO_PASSWORD = os.getenv("DEMO_PASSWORD", "demo") + # Monitoring (app/routes/ops.py): the token a monitor sends to /ops/metrics. + # Unset, the endpoint answers 404. + OPS_METRICS_TOKEN = os.getenv("OPS_METRICS_TOKEN") + # Uploads (file import) MAX_CONTENT_LENGTH = int(os.getenv("MAX_UPLOAD_MB", "10")) * 1024 * 1024 UPLOAD_MAX_AGE_HOURS = 24 diff --git a/app/routes/ops.py b/app/routes/ops.py new file mode 100644 index 0000000..c997f4c --- /dev/null +++ b/app/routes/ops.py @@ -0,0 +1,97 @@ +"""Endpoints for a monitor: ``/health`` and ``/ops/metrics``. + +``/health`` is public and says only whether the app and its database answer, and which commit +runs. ``/ops/metrics`` gives counts (never hours, dates or notes) to whoever sends +``Authorization: Bearer ``; without that setting it does not exist (404). +Both are exempt from the login guard (``PUBLIC_ENDPOINTS`` in ``app/auth.py``). +""" + +import hmac +from datetime import date, timedelta +from pathlib import Path +from typing import Optional + +from flask import Blueprint, current_app, jsonify, request +from sqlalchemy import func, text + +from app.auth import csrf +from app.db.database import db +from app.models.models import Employee, ScheduleEntry + +ops_bp = Blueprint("ops", __name__) +csrf.exempt(ops_bp) + + +def git_version(root: Path) -> Optional[str]: + """Short hash of the commit checked out in ``root``, read from ``.git``.""" + try: + head = (root / ".git" / "HEAD").read_text().strip() + if head.startswith("ref: "): + ref = head[5:] + loose = root / ".git" / ref + if loose.exists(): + return loose.read_text().strip()[:7] + for line in (root / ".git" / "packed-refs").read_text().splitlines(): + if line.endswith(" " + ref): + return line.split()[0][:7] + return None + return head[:7] + except OSError: + return None + + +@ops_bp.route("/health") +def health(): + """``ok`` and the version, or 503 when the database does not answer.""" + version = git_version(Path(current_app.root_path).parent) + try: + db.session.execute(text("SELECT 1")) + except Exception: # noqa: BLE001 - any database failure means "not healthy" + current_app.logger.exception("health: the database does not answer") + return jsonify(status="error", version=version), 503 + return jsonify(status="ok", version=version) + + +def _authorized() -> Optional[bool]: + """None when the endpoint is off; otherwise whether the request carries the token.""" + expected = current_app.config.get("OPS_METRICS_TOKEN") + if not expected: + return None + scheme, _, token = request.headers.get("Authorization", "").partition(" ") + return scheme.lower() == "bearer" and hmac.compare_digest( + token.encode(), expected.encode() + ) + + +def collect(today: date) -> list: + """Days logged in the last week (worked and absences), in total, and users.""" + week = today - timedelta(days=7) + recent = db.session.query(ScheduleEntry).filter(ScheduleEntry.date > week) + absences = recent.filter(ScheduleEntry.absence_code.isnot(None)).count() + total_recent = recent.count() + return [ + { + "name": "days_logged_7d", + "value": total_recent - absences, + "labels": {"kind": "work"}, + }, + {"name": "days_logged_7d", "value": absences, "labels": {"kind": "absence"}}, + { + "name": "days_logged_total", + "value": db.session.query(func.count(ScheduleEntry.id)).scalar(), + }, + {"name": "users", "value": db.session.query(func.count(Employee.id)).scalar()}, + ] + + +@ops_bp.route("/ops/metrics") +def metrics(): + """The counts, for whoever carries the token.""" + allowed = _authorized() + if allowed is None: + return jsonify(error="not found"), 404 + if not allowed: + response = jsonify(error="invalid or missing token") + response.headers["WWW-Authenticate"] = "Bearer" + return response, 401 + return jsonify(metrics=collect(date.today())) diff --git a/tests/test_ops.py b/tests/test_ops.py new file mode 100644 index 0000000..0cc6401 --- /dev/null +++ b/tests/test_ops.py @@ -0,0 +1,115 @@ +"""Tests for /health and /ops/metrics, the endpoints for a monitor.""" + +from datetime import date, timedelta + +import pytest + +from app import create_app +from app.config.config import Config +from app.db.database import db +from app.models.models import Employee, ScheduleEntry +from app.routes.ops import git_version + + +class GuardedConfig(Config): + TESTING = True + SQLALCHEMY_DATABASE_URI = "sqlite:///:memory:" + HOLIDAY_AUTO_FETCH = False + SECRET_KEY = "test-secret" + WTF_CSRF_ENABLED = False + OPS_METRICS_TOKEN = "s3cret" + + +@pytest.fixture +def guarded(): + """An app with the login guard on and a metrics token.""" + app = create_app(GuardedConfig) + with app.app_context(): + db.create_all() + yield app + db.session.remove() + db.drop_all() + + +def test_health_needs_no_login(guarded): + response = guarded.test_client().get("/health") + assert response.status_code == 200 + assert response.get_json()["status"] == "ok" + + +def test_metrics_needs_the_token(guarded): + client = guarded.test_client() + assert client.get("/ops/metrics").status_code == 401 + bad = client.get("/ops/metrics", headers={"Authorization": "Bearer nope"}) + assert bad.status_code == 401 + + +def test_metrics_is_off_without_a_token(app): + assert app.config.get("OPS_METRICS_TOKEN") is None + assert app.test_client().get("/ops/metrics").status_code == 404 + + +def test_metrics_counts(guarded): + employee = Employee(name="a") + db.session.add(employee) + db.session.commit() + today = date.today() + db.session.add_all( + [ + ScheduleEntry(employee_id=employee.id, date=today, entries=[]), + ScheduleEntry( + employee_id=employee.id, + date=today - timedelta(days=1), + entries=[], + absence_code="LIC", + ), + ScheduleEntry( + employee_id=employee.id, date=today - timedelta(days=40), entries=[] + ), + ] + ) + db.session.commit() + response = guarded.test_client().get( + "/ops/metrics", headers={"Authorization": "Bearer s3cret"} + ) + assert response.status_code == 200 + values = { + (m["name"], tuple(sorted((m.get("labels") or {}).items()))): m["value"] + for m in response.get_json()["metrics"] + } + assert values[("days_logged_7d", (("kind", "work"),))] == 1 + assert values[("days_logged_7d", (("kind", "absence"),))] == 1 + assert values[("days_logged_total", ())] == 3 + assert values[("users", ())] == 1 + + +def test_git_version(tmp_path): + git = tmp_path / ".git" + (git / "refs" / "heads").mkdir(parents=True) + (git / "HEAD").write_text("ref: refs/heads/main\n") + (git / "refs" / "heads" / "main").write_text("0123456789abcdef\n") + assert git_version(tmp_path) == "0123456" + (git / "refs" / "heads" / "main").unlink() + (git / "packed-refs").write_text("fedcba9876543210 refs/heads/main\n") + assert git_version(tmp_path) == "fedcba9" + assert git_version(tmp_path / "missing") is None + + +def test_health_is_503_when_the_database_fails(guarded, monkeypatch): + def broken(*args, **kwargs): + raise RuntimeError("database down") + + monkeypatch.setattr(db.session, "execute", broken) + response = guarded.test_client().get("/health") + assert response.status_code == 503 + assert response.get_json()["status"] == "error" + + +def test_git_version_detached_and_unknown_ref(tmp_path): + git = tmp_path / ".git" + git.mkdir() + (git / "HEAD").write_text("abcdef0123456789\n") + assert git_version(tmp_path) == "abcdef0" + (git / "HEAD").write_text("ref: refs/heads/other\n") + (git / "packed-refs").write_text("fedcba9876543210 refs/heads/main\n") + assert git_version(tmp_path) is None