Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
085c488f7b | ||
|
|
5c4e4dc099 | ||
|
|
93828b38e9 | ||
|
|
178a03e898 |
No files matched your search
@@ -200,8 +200,8 @@ entry in `FACEPLATES`.
|
||||
|---|---|
|
||||
| UniFi device offline (≥`unifi_failure_threshold` consecutive checks) | P2 High |
|
||||
| Proxmox host NIC link-down regression (≥2 consecutive checks) | P2 High |
|
||||
| Host unreachable via ping (≥2 consecutive checks) | P2 High |
|
||||
| Configured host has no metrics in Prometheus (host or `node_exporter` down, ≥2 consecutive checks) | P2 High |
|
||||
| Host unreachable via ping (≥`host_failure_threshold` consecutive checks) | P2 High |
|
||||
| Configured host has no metrics in Prometheus (host or `node_exporter` down, ≥`host_failure_threshold` consecutive checks) | P2 High |
|
||||
| Prometheus unavailable, so host and interface alerting is paused (≥2 consecutive checks) | P2 High |
|
||||
| ≥3 hosts simultaneously reporting interface or metrics failures | P1 Critical |
|
||||
| WAN down: broadband or optical status not Up, or PON not in O5 (≥`modem.failure_threshold`) | P1 Critical |
|
||||
@@ -280,7 +280,8 @@ Shared by both processes. Located in the working directory (`/var/www/html/prod/
|
||||
"timeout": 45
|
||||
},
|
||||
"auth": {
|
||||
"allowed_groups": ["admin"]
|
||||
"allowed_groups": ["admin"],
|
||||
"trusted_proxies": ["10.10.10.27"]
|
||||
},
|
||||
"hosts": [
|
||||
{ "name": "large1", "prometheus_instance": "10.10.10.2:9100" },
|
||||
@@ -293,6 +294,7 @@ Shared by both processes. Located in the working directory (`/var/www/html/prod/
|
||||
"monitor": {
|
||||
"poll_interval": 120,
|
||||
"failure_threshold": 2,
|
||||
"host_failure_threshold": 5,
|
||||
"unifi_failure_threshold": 5,
|
||||
"cluster_threshold": 3,
|
||||
"ping_hosts": [
|
||||
@@ -320,9 +322,11 @@ Shared by both processes. Located in the working directory (`/var/www/html/prod/
|
||||
| `pulse.worker_id` | Which Pulse worker runs ethtool collection |
|
||||
| `pulse.timeout` | Max seconds to wait for SSH collection per host |
|
||||
| `auth.allowed_groups` | Authelia groups that may access Gandalf |
|
||||
| `auth.trusted_proxies` | Addresses or CIDR ranges of the proxy that runs Authelia forward auth (NPM). Gandalf only trusts the `Remote-*` identity headers on requests from these sources, since anyone else could set them. **Required**: with no entries, every request is unauthenticated. |
|
||||
| `hosts` | Maps Prometheus instance labels → display hostnames |
|
||||
| `monitor.poll_interval` | Seconds between full check cycles (default: 120) |
|
||||
| `monitor.failure_threshold` | Consecutive failures before creating ticket (default: 2) |
|
||||
| `monitor.host_failure_threshold` | Consecutive failures before ticketing a host that has disappeared, whether it has no metrics or doesn't answer ping (default: 5). A normal reboot takes about 3-5 minutes, so the default rides it out: the host still shows as down on the dashboard, but a ticket opens only after about 8 minutes at the default poll interval. For longer maintenance, suppress the host first. |
|
||||
| `monitor.unifi_failure_threshold` | Consecutive failures before ticketing a UniFi device as offline (default: same as `failure_threshold`). Set higher than `failure_threshold` — UniFi switches/APs can take several minutes to rejoin after a firmware-update reboot, so a low threshold cuts tickets for momentary maintenance reboots instead of real failures. |
|
||||
| `monitor.cluster_threshold` | Hosts with failures to trigger cluster-wide P1 (default: 3) |
|
||||
| `monitor.ping_hosts` | Hosts checked only by ping (no node_exporter) |
|
||||
@@ -424,7 +428,7 @@ systemctl restart authelia
|
||||
### 6. NPM reverse proxy
|
||||
|
||||
- **Domain:** `gandalf.lotusguild.org`
|
||||
- **Forward to:** `http://10.10.10.61:8000` (gunicorn direct, no nginx needed on LXC)
|
||||
- **Forward to:** `http://10.10.10.61:80` (the local nginx, which forwards to gunicorn on `127.0.0.1:8000`)
|
||||
- **Forward Auth:** Authelia at `http://10.10.10.167:9091`
|
||||
- **WebSockets:** Not required
|
||||
|
||||
@@ -584,8 +588,14 @@ Take LED colors from the model's quick start guide. See the comment at the top o
|
||||
for defense-in-depth.
|
||||
- **DB parameters**: all SQL uses parameterised queries via pymysql — no string
|
||||
concatenation into SQL.
|
||||
- **Auth**: Authelia enforces admin-only access at the nginx/LXC 167 layer; the Flask
|
||||
app additionally checks the `Remote-User` header via `@require_auth`.
|
||||
- **Auth**: Authelia enforces admin-only access at the NPM/LXC 167 layer; the Flask
|
||||
app additionally checks the `Remote-User` and `Remote-Groups` headers via `@require_auth`.
|
||||
Those headers are only real when NPM sent the request, because its forward auth
|
||||
overwrites them, so a LAN host connecting to the container directly could otherwise
|
||||
claim any identity. Two layers stop that. The container's nginx site (tracked in
|
||||
pve-infra) blanks them unless the request came from NPM. The app also ignores them
|
||||
unless the source address (nginx's `X-Real-IP`, or the peer address when gunicorn is
|
||||
reached directly) is in `auth.trusted_proxies`, and it fails closed when that is unset.
|
||||
|
||||
### Known Limitations
|
||||
|
||||
|
||||
@@ -118,7 +118,44 @@ def _daemon_ok(last_check: str) -> bool:
|
||||
# Auth helpers
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _request_source() -> str:
|
||||
"""The address the request came from.
|
||||
|
||||
Gunicorn listens on loopback behind the local nginx, which overwrites X-Real-IP
|
||||
with the real peer address. A peer that isn't loopback reached gunicorn directly,
|
||||
so its own address is the source and any X-Real-IP it sent is ignored.
|
||||
"""
|
||||
peer = request.remote_addr or ''
|
||||
try:
|
||||
if ipaddress.ip_address(peer).is_loopback:
|
||||
return request.headers.get('X-Real-IP', '').strip()
|
||||
except ValueError:
|
||||
return ''
|
||||
return peer
|
||||
|
||||
|
||||
def _from_trusted_proxy() -> bool:
|
||||
"""True when the request came through the Authelia-protected proxy.
|
||||
|
||||
Only then are the Remote-* identity headers real: anyone else on the LAN could
|
||||
set them. Fails closed: with no auth.trusted_proxies configured, nobody is trusted.
|
||||
"""
|
||||
try:
|
||||
source = ipaddress.ip_address(_request_source())
|
||||
except ValueError:
|
||||
return False
|
||||
for entry in _config().get('auth', {}).get('trusted_proxies', []):
|
||||
try:
|
||||
if source in ipaddress.ip_network(entry, strict=False):
|
||||
return True
|
||||
except ValueError:
|
||||
logger.error(f'Ignoring invalid auth.trusted_proxies entry {entry!r}')
|
||||
return False
|
||||
|
||||
|
||||
def _get_user() -> dict:
|
||||
if not _from_trusted_proxy():
|
||||
return {'username': '', 'name': '', 'email': '', 'groups': []}
|
||||
return {
|
||||
'username': request.headers.get('Remote-User', ''),
|
||||
'name': request.headers.get('Remote-Name', ''),
|
||||
@@ -136,6 +173,11 @@ def require_auth(f):
|
||||
def wrapper(*args, **kwargs):
|
||||
user = _get_user()
|
||||
if not user['username']:
|
||||
if request.headers.get('Remote-User'):
|
||||
logger.warning(
|
||||
f'Ignored identity headers from untrusted source {_request_source() or "unknown"!r}; '
|
||||
f'only auth.trusted_proxies may send them'
|
||||
)
|
||||
return (
|
||||
'<h1>401 – Not authenticated</h1>'
|
||||
'<p>Please access Gandalf through '
|
||||
@@ -626,7 +668,7 @@ def api_diagnose_poll(job_id: str):
|
||||
@require_auth
|
||||
def api_avatar():
|
||||
"""Serve the current user's LDAP avatar photo (JPEG), cached to disk."""
|
||||
username = request.headers.get('Remote-User', '').strip()
|
||||
username = _get_user()['username'].strip()
|
||||
if not username:
|
||||
return '', 404
|
||||
|
||||
|
||||
+8
-3
@@ -844,6 +844,10 @@ class NetworkMonitor:
|
||||
# Use a separate, more forgiving threshold so those momentary reboots
|
||||
# don't cut tickets, while still catching genuine device failures.
|
||||
self.unifi_fail_thresh = mon.get('unifi_failure_threshold', self.fail_thresh)
|
||||
# A host's exporter stops as soon as a shutdown begins and a normal reboot
|
||||
# takes about 3-5 minutes, so wait longer than that before ticketing a host
|
||||
# that has disappeared. A NIC going down on a running host stays on fail_thresh.
|
||||
self.host_fail_thresh = mon.get('host_failure_threshold', 5)
|
||||
self.cluster_thresh = mon.get('cluster_threshold', 3)
|
||||
self.cluster_name = mon.get('cluster_name', CLUSTER_NAME)
|
||||
|
||||
@@ -940,7 +944,7 @@ class NetworkMonitor:
|
||||
host, instance,
|
||||
f'No metrics from {host} ({instance}): host or node_exporter is down ({_now_utc()})',
|
||||
)
|
||||
if not sup and consec >= self.fail_thresh and not ticket_id:
|
||||
if not sup and consec >= self.host_fail_thresh and not ticket_id:
|
||||
self._ticket_metrics_missing(event_id, host, instance, consec)
|
||||
|
||||
db.set_baseline(new_baseline)
|
||||
@@ -1107,7 +1111,7 @@ class NetworkMonitor:
|
||||
name, ip,
|
||||
f'Host {name} ({ip}) unreachable via ping ({_now_utc()})',
|
||||
)
|
||||
if not sup and consec >= self.fail_thresh and not ticket_id:
|
||||
if not sup and consec >= self.host_fail_thresh and not ticket_id:
|
||||
self._ticket_unreachable(event_id, name, ip, consec)
|
||||
else:
|
||||
db.resolve_event('host_unreachable', name, ip)
|
||||
@@ -1474,7 +1478,8 @@ class NetworkMonitor:
|
||||
def run(self) -> None:
|
||||
logger.info(
|
||||
f'Gandalf monitor started – poll_interval={self.poll_interval}s '
|
||||
f'fail_thresh={self.fail_thresh} unifi_fail_thresh={self.unifi_fail_thresh}'
|
||||
f'fail_thresh={self.fail_thresh} host_fail_thresh={self.host_fail_thresh} '
|
||||
f'unifi_fail_thresh={self.unifi_fail_thresh}'
|
||||
)
|
||||
while True:
|
||||
try:
|
||||
|
||||
+47
-2
@@ -10,7 +10,10 @@ sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
|
||||
|
||||
import app as gandalf # noqa: E402
|
||||
|
||||
AUTH = {'Remote-User': 'jared', 'Remote-Name': 'Jared V', 'Remote-Groups': 'admin'}
|
||||
PROXY = '10.0.0.27'
|
||||
# What the local nginx forwards for a request that came through the Authelia proxy
|
||||
AUTH = {'Remote-User': 'jared', 'Remote-Name': 'Jared V', 'Remote-Groups': 'admin', 'X-Real-IP': PROXY}
|
||||
CONFIG = {'auth': {'allowed_groups': ['admin'], 'trusted_proxies': [PROXY]}, 'ticket_api': {}}
|
||||
STATE = {
|
||||
'network_snapshot': json.dumps({
|
||||
'hosts': {'large1': {'ip': '10.0.0.2', 'status': 'up', 'source': 'prometheus', 'interfaces': {'eth0': 'up'}}},
|
||||
@@ -32,10 +35,52 @@ def client():
|
||||
db.count_active_events.return_value = 0
|
||||
db.get_status_summary.return_value = {'critical': 0, 'warning': 0, 'info': 0, 'resolved_24h': 0}
|
||||
db.check_suppressed.return_value = False
|
||||
with patch.object(gandalf, '_cfg', {'auth': {'allowed_groups': ['admin']}, 'ticket_api': {}}):
|
||||
with patch.object(gandalf, '_cfg', CONFIG):
|
||||
yield gandalf.app.test_client()
|
||||
|
||||
|
||||
class TestIdentityHeaderTrust:
|
||||
def test_proxy_identity_is_accepted(self, client):
|
||||
assert client.get('/api/devices', headers=AUTH).status_code == 200
|
||||
|
||||
def test_lan_client_through_nginx_cannot_claim_a_user(self, client):
|
||||
spoofed = dict(AUTH, **{'X-Real-IP': '10.0.0.99'})
|
||||
assert client.get('/api/devices', headers=spoofed).status_code == 401
|
||||
|
||||
def test_loopback_without_nginx_source_is_untrusted(self, client):
|
||||
spoofed = {k: v for k, v in AUTH.items() if k != 'X-Real-IP'}
|
||||
assert client.get('/api/devices', headers=spoofed).status_code == 401
|
||||
|
||||
def test_direct_peer_cannot_borrow_the_proxy_address(self, client):
|
||||
resp = client.get('/api/devices', headers=AUTH, environ_base={'REMOTE_ADDR': '10.0.0.99'})
|
||||
assert resp.status_code == 401
|
||||
|
||||
def test_proxy_connecting_directly_is_trusted(self, client):
|
||||
resp = client.get('/api/devices', headers=AUTH, environ_base={'REMOTE_ADDR': PROXY})
|
||||
assert resp.status_code == 200
|
||||
|
||||
def test_fails_closed_without_trusted_proxies(self, client):
|
||||
with patch.object(gandalf, '_cfg', {'auth': {'allowed_groups': ['admin']}}):
|
||||
assert client.get('/api/devices', headers=AUTH).status_code == 401
|
||||
|
||||
def test_cidr_entries_and_bad_entries(self, client):
|
||||
cfg = {'auth': {'allowed_groups': ['admin'], 'trusted_proxies': ['not-an-ip', '10.0.0.0/24']}}
|
||||
with patch.object(gandalf, '_cfg', cfg):
|
||||
assert client.get('/api/devices', headers=AUTH).status_code == 200
|
||||
|
||||
def test_garbage_source_header_is_untrusted(self, client):
|
||||
assert client.get('/api/devices', headers=dict(AUTH, **{'X-Real-IP': 'not-an-ip'})).status_code == 401
|
||||
|
||||
def test_rejection_is_logged(self, client, caplog):
|
||||
client.get('/api/devices', headers=dict(AUTH, **{'X-Real-IP': '10.0.0.99'}))
|
||||
assert "untrusted source '10.0.0.99'" in caplog.text
|
||||
|
||||
def test_avatar_ignores_untrusted_identity(self, client):
|
||||
with patch.object(gandalf, '_config', return_value=dict(CONFIG, ldap={'host': 'h', 'bind_dn': 'b'})):
|
||||
resp = client.get('/api/avatar', headers=dict(AUTH, **{'X-Real-IP': '10.0.0.99'}))
|
||||
assert resp.status_code == 401
|
||||
|
||||
|
||||
class TestPagesAndNav:
|
||||
def test_home_has_search_and_no_link_debug(self, client):
|
||||
html = client.get('/', headers=AUTH).get_data(as_text=True)
|
||||
|
||||
@@ -32,6 +32,7 @@ def mon(db):
|
||||
m = monitor.NetworkMonitor.__new__(monitor.NetworkMonitor)
|
||||
m.cfg = {}
|
||||
m.fail_thresh = 2
|
||||
m.host_fail_thresh = 5
|
||||
m.cluster_thresh = 2
|
||||
m.cluster_name = 'test-cluster'
|
||||
m.tickets = MagicMock()
|
||||
@@ -72,6 +73,7 @@ def healthy_modem(rx=-16.9, rx_status=None):
|
||||
|
||||
class TestDeadHostDetection:
|
||||
def test_host_missing_from_prometheus_alerts_and_tickets(self, mon, db):
|
||||
db.upsert_event.return_value = (1, False, 5, None)
|
||||
mon._process_interfaces({HOST_A: {'eth0': True}}, [])
|
||||
assert ('host_metrics_missing', 'beta', HOST_B) in upserted(db)
|
||||
assert 'No metrics' in mon.tickets.create.call_args.args[0]
|
||||
@@ -86,7 +88,19 @@ class TestDeadHostDetection:
|
||||
mon._process_interfaces({HOST_A: {'eth0': True}}, [])
|
||||
assert not mon.tickets.create.called
|
||||
|
||||
def test_reboot_length_outage_is_recorded_without_a_ticket(self, mon, db):
|
||||
db.upsert_event.return_value = (1, False, 4, None)
|
||||
mon._process_interfaces({HOST_A: {'eth0': True}}, [])
|
||||
assert ('host_metrics_missing', 'beta', HOST_B) in upserted(db)
|
||||
assert not mon.tickets.create.called
|
||||
|
||||
def test_interface_down_keeps_the_shorter_threshold(self, mon, db):
|
||||
db.get_baseline.return_value = {'alpha': {'eth0': 'up'}, 'beta': {'eth0': 'up'}}
|
||||
mon._process_interfaces({HOST_A: {'eth0': False}, HOST_B: {'eth0': True}}, [])
|
||||
assert 'Interface eth0 link-down' in mon.tickets.create.call_args.args[0]
|
||||
|
||||
def test_suppressed_host_gets_no_ticket(self, mon, db):
|
||||
db.upsert_event.return_value = (1, False, 5, None)
|
||||
db.check_suppressed.return_value = True
|
||||
mon._process_interfaces({HOST_A: {'eth0': True}}, [])
|
||||
assert not mon.tickets.create.called
|
||||
@@ -150,6 +164,15 @@ class TestPingUnknown:
|
||||
mon._process_ping_hosts([], {'pbs': False})
|
||||
assert ('host_unreachable', 'pbs', '10.0.0.3') in upserted(db)
|
||||
|
||||
def test_ping_host_ticket_waits_out_a_reboot(self, mon, db):
|
||||
mon.cfg = {'monitor': {'ping_hosts': [{'name': 'pbs', 'ip': '10.0.0.3'}]}}
|
||||
db.upsert_event.return_value = (1, False, 4, None)
|
||||
mon._process_ping_hosts([], {'pbs': False})
|
||||
assert not mon.tickets.create.called
|
||||
db.upsert_event.return_value = (1, False, 5, None)
|
||||
mon._process_ping_hosts([], {'pbs': False})
|
||||
assert 'Host unreachable' in mon.tickets.create.call_args.args[0]
|
||||
|
||||
|
||||
class TestUnifiRates:
|
||||
def _collector(self):
|
||||
|
||||
Reference in new issue
Block a user