Files

166 lines
7.3 KiB
Python

import io
import json
import urllib.error
import pytest
from dx_productivity.dsh.ticket_tracking import TicketTracker
from dx_productivity.dsh.git_issues import GitIssuePublisher, NoRedirect
ID = 'a' * 24
SERVER = 'https://git.example'
REPO = 'owner/repo'
URL = SERVER + '/' + REPO + '/issues/7'
def setup_ticket(root, **ticket):
directory = root / 'dsh' / 'incidents' / ID
directory.mkdir(parents=True)
(directory / 'incident.json').write_text(json.dumps({'incident_id': ID,
'ticket': {'number': 7, 'url': URL, **ticket}}), encoding='utf8')
(root / 'dsh' / 'issue-config.json').write_text(json.dumps(
{'enabled': True, 'server': SERVER, 'repository': REPO}), encoding='utf8')
def remote(monkeypatch, *, issue=None, comments=None, failure=None):
requests = []
def connection(self):
return {'enabled': True, 'server': SERVER, 'repository': REPO}, {'Authorization': 'token test-secret'}, 'test'
monkeypatch.setattr(GitIssuePublisher, 'connection', connection)
class Opener:
def open(self, request, timeout):
requests.append(request)
if failure:
raise failure
value = comments if '/comments?' in request.full_url else issue
return io.BytesIO(json.dumps(value).encode())
def build(*handlers):
assert any(isinstance(handler, NoRedirect) for handler in handlers)
return Opener()
monkeypatch.setattr('dx_productivity.dsh.ticket_tracking.urllib.request.build_opener', build)
return requests
def good_issue(**changes):
return {'number': 7, 'html_url': URL, 'title': '[DSH:' + ID + '] worker_error',
'state': 'closed', 'updated_at': '2026-10-30T01:00:00Z', 'body': 'ignored', **changes}
def test_refresh_reads_fixed_bound_issue_and_comments_scrubs_and_persists(tmp_path, monkeypatch):
setup_ticket(tmp_path)
requests = remote(monkeypatch, issue=good_issue(), comments=[{'id': 1,
'body': 'Authorization: Bearer sensitiveExample123', 'created_at': '2026-10-30T02:00:00Z',
'user': {'login': 'reviewer'}}])
result = TicketTracker(tmp_path).refresh(ID)
assert result['state'] == 'closed'
assert result['status'] == 'synced'
assert result['last_sync_at']
assert result['locally_verified'] is False
assert 'sensitiveExample123' not in json.dumps(result)
assert all(request.get_method() == 'GET' for request in requests)
assert all(request.full_url.startswith(SERVER + '/api/v1/repos/' + REPO + '/issues/7') for request in requests)
assert len(requests) == 2
assert TicketTracker(tmp_path).list_tickets() == [result]
@pytest.mark.parametrize('ticket', [{'url': 'https://evil.example/owner/repo/issues/7'},
{'url': URL + '?redirect=bad'}, {'url': URL + '/extra'}, {'number': True}, {'number': 8},
{'url': 'https://git.example/other/repo/issues/7'}, {'url': 'https://user:pass@git.example/owner/repo/issues/7'}])
def test_invalid_local_ticket_cannot_access_credentials_or_network(tmp_path, monkeypatch, ticket):
setup_ticket(tmp_path, **ticket)
def forbidden(*args):
pytest.fail('invalid ticket attempted credentials or network')
monkeypatch.setattr(GitIssuePublisher, 'connection', forbidden)
monkeypatch.setattr('urllib.request.build_opener', forbidden)
result = TicketTracker(tmp_path).refresh(ID)
assert result['status'] == 'unavailable'
assert result['error'] == 'invalid_ticket_target'
def test_remote_identity_must_match_before_comment_read_or_state_cache(tmp_path, monkeypatch):
setup_ticket(tmp_path)
requests = remote(monkeypatch, issue=good_issue(title='[DSH:other] unrelated'), comments=[])
result = TicketTracker(tmp_path).refresh(ID)
assert result['status'] == 'unavailable'
assert result['error'] == 'ticket_identity_mismatch'
assert 'state' not in result
assert len(requests) == 1
def test_network_failure_preserves_last_good_state_and_date(tmp_path, monkeypatch):
setup_ticket(tmp_path)
remote(monkeypatch, issue=good_issue(), comments=[])
first = TicketTracker(tmp_path).refresh(ID)
remote(monkeypatch, failure=urllib.error.URLError('token super-secret'))
failed = TicketTracker(tmp_path).refresh(ID)
assert failed['state'] == first['state']
assert failed['last_sync_at'] == first['last_sync_at']
assert failed['status'] == 'unavailable'
assert failed['error'] == 'URLError'
assert 'super-secret' not in json.dumps(failed)
assert failed['last_attempt_at']
assert TicketTracker(tmp_path).list_tickets() == [failed]
def test_disabled_or_missing_credentials_do_not_make_network_request(tmp_path, monkeypatch):
setup_ticket(tmp_path)
monkeypatch.setattr(GitIssuePublisher, 'connection', lambda self: (
{'enabled': True, 'server': SERVER, 'repository': REPO}, {}, 'git_not_installed'))
result = TicketTracker(tmp_path).refresh(ID)
assert result['status'] == 'unavailable'
assert result['error'] == 'git_not_installed'
listed = TicketTracker(tmp_path).list_tickets()[0]
assert listed['number'] == 7
assert listed['url'] == URL
assert listed['last_sync_at'] is None
def test_invalid_incident_id_cannot_traverse(tmp_path):
with pytest.raises(ValueError, match='invalid_incident_id'):
TicketTracker(tmp_path).refresh('../escape')
def test_recent_comments_use_bounded_last_page(tmp_path, monkeypatch):
setup_ticket(tmp_path)
requests = remote(monkeypatch, issue=good_issue(comments=51), comments=[
{'id': n, 'body': 'comment'} for n in range(40, 51)])
result = TicketTracker(tmp_path).refresh(ID)
assert 'page=3' in requests[-1].full_url
assert len(result['comments']) <= 20
def test_connection_target_change_never_sends_credentials(tmp_path, monkeypatch):
setup_ticket(tmp_path)
requests = remote(monkeypatch, issue=good_issue(), comments=[])
monkeypatch.setattr(GitIssuePublisher, 'connection', lambda self: (
{'enabled': True, 'server': 'https://evil.example', 'repository': REPO},
{'Authorization': 'token test-secret'}, 'test'))
assert TicketTracker(tmp_path).refresh(ID)['error'] == 'invalid_ticket_target'
assert not requests
def test_list_discovers_bound_existing_ticket_without_network_or_credentials(tmp_path, monkeypatch):
setup_ticket(tmp_path)
def forbidden(*args):
pytest.fail('listing cannot access credentials or network')
monkeypatch.setattr(GitIssuePublisher, 'connection', forbidden)
monkeypatch.setattr('urllib.request.build_opener', forbidden)
rows = TicketTracker(tmp_path).list_tickets()
assert len(rows) == 1
assert rows[0] == {'incident_id': ID, 'number': 7, 'url': URL,
'status': 'not_synced', 'last_sync_at': None, 'locally_verified': False}
def test_list_omits_untrusted_local_ticket_and_uses_cached_good_result(tmp_path, monkeypatch):
setup_ticket(tmp_path)
remote(monkeypatch, issue=good_issue(), comments=[])
tracker = TicketTracker(tmp_path)
cached = tracker.refresh(ID)
assert tracker.list_tickets() == [cached]
directory = tmp_path / 'dsh' / 'incidents' / ('b' * 24)
directory.mkdir()
(directory / 'incident.json').write_text(json.dumps({'incident_id': 'b' * 24,
'ticket': {'number': 7, 'url': 'https://evil.example/owner/repo/issues/7'}}), encoding='utf8')
assert tracker.list_tickets() == [cached]