Files
ss-tools/backend/tests/scripts/test_verify_dashboard_testing_current.py

132 lines
6.0 KiB
Python

# #region Test.VerifyDashboardTestingCurrent [C:2] [TYPE Module] [SEMANTICS test,freeze,privacy,launcher]
# @BRIEF SQL-free refusal and report-privacy guards for the final one-dispatch launcher; no migration or final suite is executed.
import importlib.util
import json
import logging
from pathlib import Path
import subprocess
import pytest
ROOT = Path(__file__).resolve().parents[3]
SPEC = importlib.util.spec_from_file_location('verify_current', ROOT / 'scripts/verify_dashboard_testing_current.py')
launcher = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(launcher)
@pytest.mark.parametrize('changed', [
{'host':'localhost'}, {'port':5432}, {'port':True}, {'database':'ss_tools'},
{'database':'catalog_empty_v3'}, {'username':''}, {'password':None},
])
def test_foreign_or_malformed_final_connection_refuses_privately(tmp_path, changed):
path = tmp_path / 'connection.json'
config = {'username':'private-user','password':'PRIVATE_CONNECTION_SENTINEL',
'host':'127.0.0.1','port':15439,'database':'catalog_final_empty_20261010',**changed}
path.write_text(json.dumps(config))
path.chmod(0o600)
with pytest.raises(RuntimeError, match='^FINAL_CONNECTION_SCOPE_INVALID$') as failure:
launcher.read_connection(path)
assert failure.value.__suppress_context__
assert 'PRIVATE_CONNECTION_SENTINEL' not in str(failure.value)
def test_final_connection_requires_private_file_mode_and_exact_owned_locator(tmp_path):
path = tmp_path / 'connection.json'
config = {'username':'private-user','password':'PRIVATE_CONNECTION_SENTINEL',
'host':'127.0.0.1','port':15439,'database':'catalog_final_empty_20261010'}
path.write_text(json.dumps(config))
path.chmod(0o644)
with pytest.raises(RuntimeError, match='^FINAL_CONNECTION_FILE_MODE_INVALID$'):
launcher.read_connection(path)
path.chmod(0o600)
assert launcher.read_connection(path) == config
def test_wrong_source_commit_refuses_before_any_database_import():
with pytest.raises(RuntimeError, match='^FINAL_SOURCE_COMMIT_CONFLICT$'):
launcher.check_freeze(ROOT, '0' * 40)
def test_nearby_commit_identity_is_not_accepted():
commit = subprocess.check_output(['git','rev-parse','HEAD'], cwd=ROOT, text=True).strip()
# This guard is independent of whether the surrounding checkout is dirty.
with pytest.raises(RuntimeError, match='^FINAL_SOURCE_COMMIT_CONFLICT$'):
launcher.check_freeze(ROOT, ('1' if commit[0] != '1' else '2') + commit[1:])
def test_molecular_filter_removes_credentials_and_exception_body():
safe = launcher.SafeLogs(['PRIVATE_PASSWORD_SENTINEL', 'private-user'])
try:
raise RuntimeError('[SQL: private body] PRIVATE_PASSWORD_SENTINEL')
except RuntimeError:
import sys
record = logging.LogRecord('cot', logging.ERROR, __file__, 1,
'postgresql+psycopg2://private-user:PRIVATE_PASSWORD_SENTINEL@127.0.0.1/db', (), sys.exc_info())
record.payload = {'nested':['PRIVATE_PASSWORD_SENTINEL'], 'reason':'connection_unavailable'}
assert safe.filter(record)
projected = json.dumps({'message':record.getMessage(),'payload':record.payload,'error':record.error})
assert 'PRIVATE_PASSWORD_SENTINEL' not in projected and 'private-user' not in projected
assert '[SQL:' not in projected and 'postgresql' not in projected
assert record.exc_info is None and record.error == {'failure_type':'RuntimeError'}
assert record.payload['reason'] == 'connection_unavailable'
from src.core.cot_formatter import CotJsonFormatter
wire = CotJsonFormatter().format(record)
assert 'PRIVATE_PASSWORD_SENTINEL' not in wire and '[SQL:' not in wire and 'postgresql' not in wire
assert json.loads(wire)['error'] == {'failure_type':'RuntimeError'}
def test_junit_failure_projection_keeps_type_and_stack_without_driver_message():
try:
raise RuntimeError('postgresql://user:PRIVATE_JUNIT_SENTINEL@localhost/db [SQL: body]')
except RuntimeError as exc:
observed = launcher.safe_failure(pytest.ExceptionInfo.from_exception(exc))
projection = json.loads(observed)
assert projection['failure_type'] == 'RuntimeError'
assert projection['locations'][-1]['path'] == __file__
assert projection['locations'][-1]['line'] > 0
assert 'PRIVATE_JUNIT_SENTINEL' not in observed and '[SQL:' not in observed
def test_delayed_node_observes_locations_without_locals_or_source_and_cancels_timer():
import sys
from contextvars import ContextVar
from types import SimpleNamespace
timers, events = [], []
private = 'PRIVATE_DELAYED_NODE_SENTINEL'
trace = ContextVar('test_delay_trace', default='foreign')
class Timer:
def __init__(self, seconds, callback):
assert seconds == 60
self.callback, self.cancelled, self.started = callback, False, False
timers.append(self)
def start(self):
self.started = True
def cancel(self):
self.cancelled = True
foreign = SimpleNamespace(f_code=SimpleNamespace(co_filename='https://' + private, co_name=private),
f_lineno=7, f_back=None, f_locals={'password':private})
token = trace.set('owned-node-trace')
observer = launcher.DelayedNode(ROOT, 'tests/test_current.py::test_owned',
lambda message, **event: events.append({'trace':trace.get(), **event}), timer_factory=Timer,
frames=lambda: {1:sys._getframe(), 2:foreign})
trace.reset(token)
observer.start()
observer.stage = 'call'
timers[0].callback()
assert timers[0].started
assert len(events) == 1 and events[0]['error_code'] == 'FINAL_NODE_DELAYED'
assert events[0]['trace'] == 'owned-node-trace'
assert events[0]['payload']['stage'] == 'call'
assert {'file':'outside_source_roots','line':7,'function':'unavailable'} in events[0]['payload']['locations']
wire = json.dumps(events)
assert private not in wire and 'password' not in wire and 'https://' not in wire
observer.finish()
assert timers[0].cancelled
timers[0].callback()
assert len(events) == 1
# #endregion Test.VerifyDashboardTestingCurrent