Thor contract, part 1: [gandalf] title tag and a read-only API key for Thor
Lint / JS (eslint) (push) Successful in 14s
Lint / Python (flake8) (push) Successful in 1m47s
Lint / Notify on failure (push) Skipped
Lint / Deploy (push) Skipped
Security / Python Security (bandit) (push) Successful in 1m48s
Lint / JS (eslint) (pull_request) Successful in 12s
Lint / Python (flake8) (pull_request) Successful in 1m0s
Lint / Notify on failure (pull_request) Skipped
Lint / Deploy (pull_request) Skipped
Security / Python Security (bandit) (pull_request) Successful in 1m21s
Test / Python Tests (pytest) (pull_request) Successful in 1m43s
Test / Python Tests (pytest) (push) Successful in 1m6s
Lint / JS (eslint) (push) Successful in 14s
Lint / Python (flake8) (push) Successful in 1m47s
Lint / Notify on failure (push) Skipped
Lint / Deploy (push) Skipped
Security / Python Security (bandit) (push) Successful in 1m48s
Lint / JS (eslint) (pull_request) Successful in 12s
Lint / Python (flake8) (pull_request) Successful in 1m0s
Lint / Notify on failure (pull_request) Skipped
Lint / Deploy (pull_request) Skipped
Security / Python Security (bandit) (pull_request) Successful in 1m21s
Test / Python Tests (pytest) (pull_request) Successful in 1m43s
Test / Python Tests (pytest) (push) Successful in 1m6s
Titles move to the shared standard [source][auto][gandalf][network] Summary [scope][production][issue], built in one place (ticket_text.title). Checked by running Tinker's TicketHash.php: every Gandalf title shape hashes the same as before, so open tickets keep matching. Thor can read /api/status, /api/events, /api/attention and /api/suppressions with a machine key (Authorization: Bearer, only its SHA-256 in config, read-only, optional source CIDRs; a wrong key is a 401 and never falls back to identity headers). /api/suppressions ?include_ended=1&hours=N returns every suppression in force in the window with start, planned end, actual end and who ended it: new ended_at/ended_by columns, added automatically. Refs #66 (items 1 and 2) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
bf5d36ed1e
commit
f924ce42c3
9 files changed
+391
-25
No files matched your search
+72
-1
@@ -135,6 +135,77 @@ class TestPagesAndNav:
|
||||
assert client.get('/api/links', headers=AUTH).status_code == 200
|
||||
|
||||
|
||||
import hashlib # noqa: E402
|
||||
|
||||
THOR_KEY = 'test-thor-key-not-real'
|
||||
KEYS = [{'name': 'thor', 'sha256': hashlib.sha256(THOR_KEY.encode()).hexdigest(), 'scopes': ['read']}]
|
||||
BEARER = {'Authorization': f'Bearer {THOR_KEY}'}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def key_client(client):
|
||||
with patch.object(gandalf, '_cfg', dict(CONFIG, api_keys=KEYS)):
|
||||
yield client
|
||||
|
||||
|
||||
class TestMachineKey:
|
||||
"""gandalf#66: Thor reads status, events, attention and suppressions with a read-only key."""
|
||||
|
||||
def test_reads_with_the_key(self, key_client):
|
||||
for url in ('/api/status', '/api/events', '/api/attention', '/api/suppressions'):
|
||||
assert key_client.get(url, headers=BEARER).status_code == 200, url
|
||||
|
||||
def test_wrong_key_is_refused_even_with_identity_headers(self, key_client):
|
||||
resp = key_client.get('/api/status', headers=dict(AUTH, Authorization='Bearer nope'))
|
||||
assert resp.status_code == 401 and resp.get_json()['error'] == 'Invalid API key'
|
||||
|
||||
def test_key_opens_only_the_marked_routes(self, key_client):
|
||||
assert key_client.get('/api/devices', headers=BEARER).status_code == 401
|
||||
assert key_client.get('/', headers=BEARER).status_code == 401
|
||||
|
||||
def test_key_cannot_write(self, key_client):
|
||||
resp = key_client.post('/api/suppressions', headers=BEARER, json={'target_type': 'all', 'reason': 'x'})
|
||||
assert resp.status_code in (401, 403, 405)
|
||||
assert not gandalf.db.create_suppression.called
|
||||
|
||||
def test_no_key_configured_means_no_key_works(self, client):
|
||||
assert client.get('/api/status', headers=BEARER).status_code == 401
|
||||
|
||||
def test_key_without_read_scope(self, client):
|
||||
keys = [dict(KEYS[0], scopes=[])]
|
||||
with patch.object(gandalf, '_cfg', dict(CONFIG, api_keys=keys)):
|
||||
assert client.get('/api/status', headers=BEARER).status_code == 401
|
||||
|
||||
def test_source_restriction(self, client):
|
||||
keys = [dict(KEYS[0], sources=['10.10.10.0/24'])]
|
||||
with patch.object(gandalf, '_cfg', dict(CONFIG, api_keys=keys)):
|
||||
inside = client.get('/api/status', headers=BEARER, environ_base={'REMOTE_ADDR': '10.10.10.70'})
|
||||
outside = client.get('/api/status', headers=BEARER, environ_base={'REMOTE_ADDR': '192.168.1.5'})
|
||||
assert inside.status_code == 200 and outside.status_code == 401
|
||||
|
||||
def test_users_still_sign_in_as_before(self, key_client):
|
||||
assert key_client.get('/api/status', headers=AUTH).status_code == 200
|
||||
assert key_client.get('/api/status').status_code == 401
|
||||
|
||||
def test_ended_suppressions_for_thor(self, key_client):
|
||||
gandalf.db.get_suppression_windows.return_value = [{'id': 2, 'state': 'expired'}]
|
||||
data = key_client.get('/api/suppressions?include_ended=1&hours=48', headers=BEARER).get_json()
|
||||
assert data['suppressions'] == [{'id': 2, 'state': 'expired'}] and data['since'].endswith('Z')
|
||||
since = gandalf.db.get_suppression_windows.call_args.args[0]
|
||||
assert 47.9 < (datetime.utcnow() - since).total_seconds() / 3600 < 48.1
|
||||
|
||||
def test_ended_suppressions_bad_hours(self, key_client):
|
||||
for h in ('x', '0', '800'):
|
||||
assert key_client.get(f'/api/suppressions?include_ended=1&hours={h}', headers=BEARER).status_code == 400
|
||||
|
||||
def test_stalled_cluster_warning_reaches_thor(self, key_client):
|
||||
stalled = {'event_type': 'cluster_hosts_stalled', 'severity': 'warning', 'target_name': 'proxmox-cluster',
|
||||
'target_detail': '', 'description': '3 hosts stopped answering ... OOM kills on compute-storage-01'}
|
||||
gandalf.db.get_active_events.return_value = [stalled]
|
||||
events = key_client.get('/api/events', headers=BEARER).get_json()['active']
|
||||
assert events[0]['event_type'] == 'cluster_hosts_stalled' and 'OOM' in events[0]['description']
|
||||
|
||||
|
||||
class TestDeviceApi:
|
||||
def test_requires_auth(self, client):
|
||||
assert client.get('/api/devices').status_code == 401
|
||||
@@ -974,7 +1045,7 @@ class TestModemRestart:
|
||||
def test_failed_restart_undoes_the_silence(self, client):
|
||||
resp, km, _ = self._post(client, restart=gandalf.modem_api.ModemUnreachable('timeout'))
|
||||
assert resp.status_code == 502
|
||||
gandalf.db.deactivate_suppression.assert_called_once_with(42)
|
||||
gandalf.db.deactivate_suppression.assert_called_once_with(42, ended_by='jared')
|
||||
assert km.call_args_list[-1].args == (self.CFG['uptime_kuma'], False)
|
||||
|
||||
def test_one_at_a_time(self, client):
|
||||
|
||||
@@ -84,3 +84,62 @@ class TestPowerFeeds:
|
||||
'updated_at': NOW}])
|
||||
with patcher:
|
||||
assert db.get_power_feeds()[0]['updated_at'] == '2026-11-14T12:00:00Z'
|
||||
|
||||
|
||||
class TestSuppressionWindows:
|
||||
"""gandalf#66: Thor reads every suppression with its start and end to tell planned windows
|
||||
from outages. 2026-11-25: the only record the rack maintenance was planned was row 2."""
|
||||
|
||||
@staticmethod
|
||||
def _row(i, created_h, expires_h=None, ended_h=None, active=False, ended_by=''):
|
||||
now = datetime.utcnow()
|
||||
at = lambda h: None if h is None else now - timedelta(hours=h) # noqa: E731
|
||||
return {'id': i, 'target_type': 'all', 'target_name': '', 'target_detail': '', 'reason': 'switch update',
|
||||
'suppressed_by': 'jared', 'created_at': at(created_h), 'expires_at': at(expires_h),
|
||||
'ended_at': at(ended_h), 'ended_by': ended_by, 'active': active}
|
||||
|
||||
def _windows(self, rows):
|
||||
db._suppression_schema_ready = True
|
||||
patcher, cur = _fake_conn(rows)
|
||||
with patcher:
|
||||
return db.get_suppression_windows(datetime.utcnow() - timedelta(hours=24))
|
||||
|
||||
def test_expired_window_has_its_end(self):
|
||||
[w] = self._windows([self._row(2, 12, expires_h=11.5, ended_h=11.5, ended_by='expired')])
|
||||
assert w['state'] == 'expired' and w['end_known'] and w['ended_by'] == 'expired'
|
||||
assert w['started_at'].endswith('Z') and w['ended_at'] == w['expires_at']
|
||||
|
||||
def test_removed_by_hand_before_expiry(self):
|
||||
[w] = self._windows([self._row(3, 5, expires_h=1, ended_h=4, ended_by='jared')])
|
||||
assert w['state'] == 'ended' and w['ended_by'] == 'jared' and w['ended_at'] != w['expires_at']
|
||||
|
||||
def test_active_has_no_end(self):
|
||||
[w] = self._windows([self._row(4, 1, active=True)])
|
||||
assert w['state'] == 'active' and w['ended_at'] is None and w['end_known']
|
||||
|
||||
def test_expired_but_not_yet_cleaned_up(self):
|
||||
[w] = self._windows([self._row(5, 3, expires_h=2, active=True)])
|
||||
assert w['state'] == 'expired' and w['ended_at'] == w['expires_at'] and w['ended_by'] == 'expired'
|
||||
|
||||
def test_removed_before_end_times_were_recorded(self):
|
||||
[w] = self._windows([self._row(6, 6)])
|
||||
assert w['state'] == 'ended' and not w['end_known'] and w['ended_at'] is None
|
||||
|
||||
def test_deactivate_records_who_and_when(self):
|
||||
db._suppression_schema_ready = True
|
||||
patcher, cur = _fake_conn([])
|
||||
with patcher:
|
||||
db.deactivate_suppression(7, ended_by='jared')
|
||||
sql, args = cur.execute.call_args.args
|
||||
assert 'ended_at=NOW()' in sql and 'ended_by=%s' in sql and args == ('jared', 7)
|
||||
|
||||
def test_schema_adds_the_columns_once(self):
|
||||
db._suppression_schema_ready = False
|
||||
patcher, cur = _fake_conn([{'Field': 'id'}, {'Field': 'active'}])
|
||||
with patcher:
|
||||
db.ensure_suppression_schema()
|
||||
db.ensure_suppression_schema()
|
||||
sqls = [c.args[0] for c in cur.execute.call_args_list]
|
||||
assert sum('ADD COLUMN ended_at' in q for q in sqls) == 1
|
||||
assert sum('ADD COLUMN ended_by' in q for q in sqls) == 1
|
||||
assert db._suppression_schema_ready
|
||||
@@ -1096,7 +1096,7 @@ class TestTicketContext:
|
||||
mon.unifi_fail_thresh = 3
|
||||
self._mon(mon)._ticket_unifi(1, {'name': 'ap1', 'type': 'uap', 'model': 'U6', 'ip': '1.2.3.4'})
|
||||
assert mon.tickets.create.call_args.args[0] == \
|
||||
'[ap1][auto][production][issue][network][single-node] UniFi device offline'
|
||||
'[ap1][auto][gandalf][network] UniFi device offline [single-node][production][issue]'
|
||||
|
||||
def test_remember_uplinks_saves_only_on_change(self, mon, db):
|
||||
self._mon(mon)
|
||||
@@ -1487,7 +1487,7 @@ class TestFinishModemRestart:
|
||||
def test_back_ends_kuma_and_the_silence(self, mon, db):
|
||||
out, km = self._run(mon, db, self._restart(300), {'reachable': True, 'wan_problems': [], 'uptime_s': 200})
|
||||
km.assert_called_once_with({'url': 'http://kuma.test'}, False)
|
||||
db.deactivate_suppression.assert_called_once_with(9)
|
||||
db.deactivate_suppression.assert_called_once_with(9, ended_by='gandalf')
|
||||
assert out['back'] and out['rebooted'] and out['back_after_s'] == 300 and out['finished_at'] == self.NOW
|
||||
|
||||
def test_waits_while_the_modem_is_down(self, mon, db):
|
||||
@@ -1505,7 +1505,7 @@ class TestFinishModemRestart:
|
||||
def test_gives_up_after_half_an_hour(self, mon, db):
|
||||
out, km = self._run(mon, db, self._restart(1900), {'reachable': False})
|
||||
assert out['back'] is False and out['back_after_s'] is None and km.called
|
||||
db.deactivate_suppression.assert_called_once_with(9)
|
||||
db.deactivate_suppression.assert_called_once_with(9, ended_by='gandalf')
|
||||
|
||||
def test_kuma_failure_retries_next_cycle(self, mon, db):
|
||||
out, _ = self._run(mon, db, self._restart(300), {'reachable': True, 'wan_problems': [], 'uptime_s': 200},
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
"""Tests for ticket_text.py: the Markdown Gandalf puts in tickets."""
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
import pytest
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
|
||||
|
||||
import ticket_text as tt # noqa: E402
|
||||
@@ -62,3 +65,32 @@ def test_recovery_comment():
|
||||
assert '- **Lasted:** 7 min (first seen 2026-11-10 17:53 UTC)' in text
|
||||
assert '- **Gandalf:** https://g/device/large1' in text
|
||||
assert 'leaves this ticket open' in text
|
||||
|
||||
|
||||
class TestTitle:
|
||||
"""The shared title standard (thor#1, gandalf#66): [source][auto][app][area] Summary [scope][env][type]."""
|
||||
|
||||
@staticmethod
|
||||
def _hash_parts(title):
|
||||
# What Tinker's TicketHash.php reads from an automated network title: the first tag, the
|
||||
# environment and scope tags, and the text outside the tags. Same title parts, same ticket.
|
||||
tags = re.findall(r'\[([^\]]+)\]', title)
|
||||
env = sorted(t for t in tags if t in ('production', 'development', 'staging', 'single-node', 'cluster-wide'))
|
||||
heading = re.sub(r'\[[^\]]*\]', '', title).strip(' -\t')
|
||||
return tags[0], '[auto]' in title, 'network' in title.lower(), env, heading
|
||||
|
||||
def test_format(self):
|
||||
assert tt.title('monitor-01', 'Interface enp3s0 link-down') == \
|
||||
'[monitor-01][auto][gandalf][network] Interface enp3s0 link-down [single-node][production][issue]'
|
||||
assert tt.title('att-modem', 'WAN down', 'cluster-wide').endswith('WAN down [cluster-wide][production][issue]')
|
||||
|
||||
def test_hashes_like_the_old_format(self):
|
||||
for source, summary, scope in (('monitor-01', 'Interface enp3s0 link-down', 'single-node'),
|
||||
('att-modem', 'Internet degraded (high latency or packet loss)', 'cluster-wide'),
|
||||
('24RJ45-POE', 'Cable C07 does not match the cutsheet', 'single-node')):
|
||||
old = f'[{source}][auto][production][issue][network][{scope}] {summary}'
|
||||
assert self._hash_parts(tt.title(source, summary, scope)) == self._hash_parts(old)
|
||||
|
||||
def test_unknown_scope_is_refused(self):
|
||||
with pytest.raises(ValueError):
|
||||
tt.title('x', 'y', 'rack')
|
||||
Reference in new issue
Block a user