import time import jwt import pytest from cryptography.hazmat.primitives.asymmetric import rsa from thor.config import Settings from thor.web.app import create_app from thor.web.mcp import CLIENT_ID, ISSUER, READ, WRITE from .fakes import Clock, FakeStore T = 1_795_412_400.0 KEY = rsa.generate_private_key(public_exponent=65537, key_size=2048) OTHER = rsa.generate_private_key(public_exponent=65537, key_size=2048) class StaticJWKS: """Stands in for PyJWKClient: always returns our test public key.""" class _K: key = KEY.public_key() def get_signing_key_from_jwt(self, token): return self._K() def token(*, scopes=(READ, WRITE), groups=('admin',), aud='https://thor.example/mcp', client=CLIENT_ID, typ='at+jwt', signer=KEY, exp_in=600, user='jared'): now = int(time.time()) claims = {'iss': ISSUER, 'sub': 'uuid-1', 'aud': aud, 'exp': now + exp_in, 'iat': now, 'client_id': client, 'scp': list(scopes), 'groups': list(groups), 'preferred_username': user} return jwt.encode(claims, signer, algorithm='RS256', headers={'typ': typ}) @pytest.fixture def app(): store = FakeStore() store.incidents['host:compute-storage-01:oom'] = { 'key': 'host:compute-storage-01:oom', 'kind': 'oom', 'subject': 'compute-storage-01', 'state': 'open', 'priority': 1, 'mode': 'shadow', 'ticket': True, 'summary': 'Out of memory', 'first_seen': T - 600, 'last_seen': T - 60, 'symptoms': {}, 'events': [], 'facts': {}} store.incidents['maintenance:gandalf:2'] = dict(store.incidents['host:compute-storage-01:oom'], key='maintenance:gandalf:2', ticket=False) s = Settings() s.public_url = 'https://thor.example' a = create_app(s, store, 'abc123', clock=Clock(T)) a.config['THOR_JWKS'] = StaticJWKS() return a def rpc(app, method, params=None, tok=None, rid=1): body = {'jsonrpc': '2.0', 'method': method, 'params': params or {}} if rid is not None: body['id'] = rid return app.test_client().post('/mcp', json=body, headers={'Authorization': f'Bearer {tok or token()}'}) def call(app, name, args=None, tok=None): r = rpc(app, 'tools/call', {'name': name, 'arguments': args or {}}, tok) res = r.get_json()['result'] return res['isError'], res['content'][0]['text'] def test_protected_resource_metadata(app): for path in ('/.well-known/oauth-protected-resource/mcp', '/.well-known/oauth-protected-resource'): d = app.test_client().get(path).get_json() assert d['resource'] == 'https://thor.example/mcp' assert d['authorization_servers'] == [ISSUER] and d['scopes_supported'] == [READ, WRITE] @pytest.mark.parametrize('bad', [ token(aud='https://wiki.lotusguild.org/mcp'), token(client='tinker-tickets-mcp'), token(typ='JWT'), token(signer=OTHER), token(exp_in=-60), token(scopes=('wiki:read',)), 'not-a-jwt', ]) def test_bad_tokens_get_401_with_resource_metadata(app, bad): r = rpc(app, 'ping', tok=bad) assert r.status_code == 401 assert 'resource_metadata="https://thor.example/.well-known/oauth-protected-resource/mcp"' in \ r.headers['WWW-Authenticate'] def test_no_token_and_wrong_group(app): r = app.test_client().post('/mcp', json={'jsonrpc': '2.0', 'id': 1, 'method': 'ping'}, headers={'Remote-User': 'jared'}) # headers are never trusted assert r.status_code == 401 assert rpc(app, 'ping', tok=token(groups=('employee',))).status_code == 403 def test_initialize_ping_and_notifications(app): r = rpc(app, 'initialize', {'protocolVersion': '2025-03-26'}).get_json()['result'] assert r['protocolVersion'] == '2025-03-26' and r['serverInfo']['name'] == 'thor' assert rpc(app, 'initialize', {'protocolVersion': '1999'}).get_json()['result']['protocolVersion'] == '2025-06-18' assert rpc(app, 'ping').get_json()['result'] == {} assert rpc(app, 'notifications/initialized', rid=None).status_code == 202 assert rpc(app, 'nope').get_json()['error']['code'] == -32601 def test_tools_list_follows_scopes(app): full = {t['name'] for t in rpc(app, 'tools/list').get_json()['result']['tools']} assert {'list_incidents', 'add_known_condition', 'attach_ticket'} <= full read = {t['name'] for t in rpc(app, 'tools/list', tok=token(scopes=(READ,))).get_json()['result']['tools']} assert 'add_known_condition' not in read and 'what_covers' in read err = rpc(app, 'tools/call', {'name': 'add_known_condition', 'arguments': {}}, token(scopes=(READ,))) assert err.get_json()['error']['code'] == -32001 def test_read_tools(app): assert not call(app, 'list_incidents', {'include_recent': False})[0] is_err, text = call(app, 'get_incident', {'key': 'host:compute-storage-01:oom'}) assert not is_err and '"links": []' in text assert call(app, 'get_incident', {'key': 'nope'})[0] is_err, text = call(app, 'what_covers', {'host': 'large1'}) assert not is_err and '693930698' in text and 'compute-storage-02' in text assert call(app, 'what_covers', {})[0] assert not call(app, 'thor_status')[0] assert '693930698' in call(app, 'list_known_conditions')[1] unknown = rpc(app, 'tools/call', {'name': 'nope'}).get_json() assert unknown['error']['code'] == -32602 def test_known_condition_tools_validate_and_record_who(app): store = app.config['THOR_STORE'] assert call(app, 'add_known_condition', {'kind': 'Reboot!', 'subject': 'pbs', 'reason': 'long enough'})[0] assert call(app, 'add_known_condition', {'kind': 'reboot', 'subject': 'pbs', 'reason': 'short'})[0] assert call(app, 'add_known_condition', {'kind': 'reboot', 'subject': 'pbs', 'ticket_id': 'abc', 'reason': 'long enough reason'})[0] is_err, text = call(app, 'add_known_condition', {'kind': 'reboot', 'subject': 'micro1', 'ticket_id': '12345', 'reason': 'flaky NIC, tracked in 12345'}) assert not is_err added = store.known[-1] assert (added['subject'], added['created_by'], added['ticket_id']) == ('monitor-01', 'jared', '12345') assert not call(app, 'end_known_condition', {'id': added['id']})[0] assert call(app, 'end_known_condition', {'id': added['id']})[0] # already ended assert call(app, 'end_known_condition', {'id': 'x'})[0] def test_attach_and_detach(app): store = app.config['THOR_STORE'] is_err, text = call(app, 'attach_ticket', {'key': 'host:compute-storage-01:oom', 'ticket_id': '615797777'}) assert not is_err and 'shadow' in text assert store.links[0]['added_by'] == 'jared' a = store.actions[-1] assert a['kind'] == 'attach' and a['status'] == 'shadow' and a['payload']['ticket_id'] == '615797777' assert call(app, 'attach_ticket', {'key': 'maintenance:gandalf:2', 'ticket_id': '1'})[0] assert call(app, 'attach_ticket', {'key': 'host:compute-storage-01:oom', 'ticket_id': 'x'})[0] assert call(app, 'attach_ticket', {'key': 'nope', 'ticket_id': '1'})[0] assert not call(app, 'detach_ticket', {'key': 'host:compute-storage-01:oom', 'ticket_id': '615797777'})[0] assert call(app, 'detach_ticket', {'key': 'host:compute-storage-01:oom', 'ticket_id': '615797777'})[0] def test_database_away_is_a_tool_error_not_a_crash(app): app.config['THOR_STORE'].down = True is_err, text = call(app, 'list_incidents') assert is_err and 'database' in text def test_batches_get_and_garbage(app): c = app.test_client() auth = {'Authorization': f'Bearer {token()}'} r = c.post('/mcp', json=[{'jsonrpc': '2.0', 'id': 1, 'method': 'ping'}, {'jsonrpc': '2.0', 'method': 'notifications/initialized'}], headers=auth) assert len(r.get_json()) == 1 assert c.post('/mcp', json=[{'jsonrpc': '2.0', 'method': 'x'}], headers=auth).status_code == 202 assert c.post('/mcp', data='{', headers=dict(auth, **{'Content-Type': 'application/json'})).status_code == 400 assert c.post('/mcp', json='just a string', headers=auth).status_code == 400 assert c.get('/mcp').status_code == 405