import hashlib import pytest from thor.config import Settings from thor.web import views from thor.web.api import check_key from thor.web.app import create_app from .fakes import Clock, FakeStore KEY = 'gandalf-test-key' T = 1_795_412_400.0 def settings(**kw): s = Settings() s.public_url = 'https://thor.example' s.api_keys = [{'name': 'gandalf', 'sha256': hashlib.sha256(KEY.encode()).hexdigest(), 'scopes': ['read'], 'sources': ['10.10.10.61/32']}] for k, v in kw.items(): setattr(s, k, v) return s def inc(key, subject, state='open', mode='shadow', ticket=True, kind='oom', priority=1, **kw): d = {'key': key, 'kind': kind, 'subject': subject, 'state': state, 'priority': priority, 'mode': mode, 'ticket': ticket, 'summary': f'{subject} {kind}', 'first_seen': T - 600, 'last_seen': T - 60, 'symptoms': {}, 'events': [{'at': T - 600, 'text': 'kill'}], 'facts': {}} d.update(kw) return d @pytest.fixture def store(): s = FakeStore() s.incidents = { 'host:compute-storage-01:oom': inc('host:compute-storage-01:oom', 'compute-storage-01'), 'cluster:corosync:partition': inc('cluster:corosync:partition', 'cluster', mode='live', kind='partition'), 'maintenance:gandalf:2': inc('maintenance:gandalf:2', 'cluster', ticket=False, kind='maintenance'), 'host:storage-01:oom': inc('host:storage-01:oom', 'storage-01', state='cleared', cleared_at=T - 30), } s.add_action({'incident_key': 'cluster:corosync:partition', 'kind': 'open', 'created': T - 500, 'mode': 'live', 'payload': {'title': 't', 'description': 'd', 'priority': 1}}) s.mark_action_sent(1, '987654321', T - 499) s.state['last_good_cycle'] = T - 30 s.state['last_cycle'] = {'started': T - 31, 'finished': T - 30, 'blind': [], 'catching_up': False} s.sources = {'loki': {'up': False, 'since': T - 120, 'last_ok': None, 'last_error': 'HTTP 500'}, 'prometheus': {'up': True, 'since': T - 9000, 'last_ok': T - 30, 'last_error': ''}} s.observations['host:monitor-01:scrape'] = { 'key': 'host:monitor-01:scrape', 'kind': 'scrape', 'role': 'symptom', 'subject': 'monitor-01', 'start': T - 100, 'end': T - 90, 'summary': 'monitor-01 slow'} return s def client(store, **kw): return create_app(settings(**kw), store, 'abc1234def', clock=Clock(T)).test_client() def get(c, path, key=KEY, ip='10.10.10.61'): headers = {'X-Forwarded-For': ip} if key: headers['Authorization'] = f'Bearer {key}' return c.get(path, headers=headers) # -- API keys ------------------------------------------------------------------ def test_api_needs_a_valid_key_from_an_allowed_address(store): c = client(store) assert get(c, '/api/incidents', key=None).status_code == 401 assert get(c, '/api/incidents', key='wrong').status_code == 401 assert get(c, '/api/incidents', ip='10.10.10.99').status_code == 401 assert get(c, '/api/incidents').status_code == 200 assert c.post('/api/incidents', headers={'Authorization': f'Bearer {KEY}'}).status_code == 405 # Identity headers never stand in for a key. spoof = {'Remote-User': 'jared', 'X-Forwarded-For': '10.10.10.27'} assert c.get('/api/incidents', headers=spoof).status_code == 401 def test_check_key_edge_cases(): s = settings() s.api_keys.append({'name': 'noread', 'sha256': hashlib.sha256(b'k2').hexdigest(), 'scopes': ['write']}) s.api_keys.append({'name': 'any', 'sha256': hashlib.sha256(b'k3').hexdigest()}) assert check_key(s, 'Bearer k2', '1.2.3.4') is None assert check_key(s, 'Bearer k3', 'not-an-ip')['name'] == 'any' assert check_key(s, f'Bearer {KEY}', 'garbage') is None assert check_key(s, 'Basic x', '10.10.10.61') is None # -- /covering (thor#1 contract, docs/contract.md) --------------------------------- def test_covering_shadow_incident_is_listed_but_does_not_cover(store): store.incidents.pop('cluster:corosync:partition') body = get(client(store), '/api/incidents/covering?host=compute-storage-01').get_json() assert body['covered'] is False and body['ticket_id'] is None assert [i['key'] for i in body['incidents']] == ['host:compute-storage-01:oom'] assert body['incidents'][0]['mode'] == 'shadow' def test_covering_live_ticket_covers_and_cluster_incidents_cover_every_host(store): body = get(client(store), '/api/incidents/covering?host=monitor-01').get_json() assert body['covered'] is True and body['ticket_id'] == '987654321' assert [i['key'] for i in body['incidents']] == ['cluster:corosync:partition'] # Timeline-only maintenance is never offered as something to comment on. assert all(i['key'] != 'maintenance:gandalf:2' for i in body['incidents']) def test_covering_known_condition_and_old_names(store): store.incidents = {} body = get(client(store), '/api/incidents/covering?host=large1').get_json() assert body['host'] == 'compute-storage-02' assert body['covered'] is True and body['ticket_id'] == '693930698' assert body['known_conditions'][0]['kind'] == 'reboot' def test_covering_scopes_and_errors(store): c = client(store) cluster = get(c, '/api/incidents/covering?scope=cluster').get_json() assert {i['key'] for i in cluster['incidents']} == {'host:compute-storage-01:oom', 'cluster:corosync:partition'} source = get(c, '/api/incidents/covering?scope=source:prometheus').get_json() assert source['covered'] is False and source['incidents'] == [] assert get(c, '/api/incidents/covering').status_code == 400 store.down = True assert get(c, '/api/incidents/covering?host=monitor-01').status_code == 503 # callers fail open def test_incident_api(store): c = client(store) assert get(c, '/api/incident/host:compute-storage-01:oom').get_json()['incident']['summary'] == \ 'compute-storage-01 oom' assert get(c, '/api/incident/none').status_code == 404 listing = get(c, '/api/incidents').get_json() assert {i['key'] for i in listing['active']} == {'cluster:corosync:partition', 'host:compute-storage-01:oom', 'maintenance:gandalf:2'} assert [i['key'] for i in listing['recent']] == ['host:storage-01:oom'] # -- pages ----------------------------------------------------------------------- def test_needs_attention_page(store): r = client(store).get('/') html = r.get_data(as_text=True) assert r.status_code == 200 assert 'nonce-' in r.headers['Content-Security-Policy'] assert 'compute-storage-01 oom' in html and 'shadow (not sent)' in html assert 'ticket #987654321' in html assert 'Loki: blind' in html and 'HTTP 500' in html assert 'On the timeline only' in html and 'monitor-01 slow' in html # unexplained symptom assert 'Last 7 days' in html and 'storage-01 oom' in html assert 'id="lt-theme-btn"' in html and 'lt.theme.toggle()' in html # light/dark switch assert 'Total Hardware
Operations Resolver' in html def test_incident_and_known_pages(store): c = client(store) r = c.get('/incident/cluster:corosync:partition') assert r.status_code == 200 and '#987654321' in r.get_data(as_text=True) assert 'timeline only' in c.get('/incident/maintenance:gandalf:2').get_data(as_text=True) assert c.get('/incident/nope').status_code == 404 known = c.get('/known').get_data(as_text=True) assert '693930698' in known and 'compute-storage-02' in known def test_user_shown_only_from_the_proxy(store): c = client(store) headers = {'Remote-User': 'jared', 'Remote-Name': 'Jared', 'Remote-Groups': 'admin,employee'} via_npm = c.get('/', headers=dict(headers, **{'X-Forwarded-For': '10.10.10.27'})).get_data(as_text=True) assert 'Jared' in via_npm and 'lt-badge-admin' in via_npm direct = c.get('/', headers=dict(headers, **{'X-Forwarded-For': '10.10.10.99'})).get_data(as_text=True) assert 'Jared' not in direct def test_explained_symptoms_are_not_listed_as_unexplained(store): store.incidents['host:compute-storage-01:oom']['symptoms'] = {'host:monitor-01:scrape': {'first': T}} data = views.needs_attention(store, settings(), T) assert data['loose'] == [] def test_filters(): from thor.web.ui import ago, hm, pclass, utc app = create_app(settings(), FakeStore(), 'x', clock=Clock(T)) with app.test_request_context('/'): assert utc(None) == 'unknown' and hm(None) == '?' and ago(None) == 'never' assert ago(T - 30) == '30 s ago' and ago(T - 600) == '10 min ago' assert ago(T - 7200) == '2 h ago' and ago(T - 3 * 86400) == '3 d ago' assert pclass(1) == 'bad' and pclass(3) == 'warn' and pclass(9) == 'info'