from pathlib import Path import pytest from gti_discovery.firebird_connection import ( AUTHORIZED_DATABASE_PATH, _FirebirdAdapter, connect_authorized_read_only, get_database_identity, validate_authorized_database_path, _ADAPTER_CREATION_TOKEN, _create_firebird_adapter, ) from gti_discovery.catalog import FirebirdCatalog from gti_discovery.firebird_queries import _ADAPTER_REGISTRATION_TOKEN, _register_approved_adapter def test_authorized_path_is_the_project_target(): assert AUTHORIZED_DATABASE_PATH == Path( r"D:\PROJETOS\GTISISTEMAS\Projeto\TESTESOFICIAIS.FDB" ) def test_validation_normalizes_case_and_relative_segments(tmp_path): target = tmp_path / "TESTESOFICIAIS.FDB" target.write_bytes(b"database") # The production target is fixed; this exercises the same normalization # rules with a temporary target without opening a database. from gti_discovery import firebird_connection original = firebird_connection.AUTHORIZED_DATABASE_PATH firebird_connection.AUTHORIZED_DATABASE_PATH = target try: assert validate_authorized_database_path( tmp_path / "sub" / ".." / "testesoficiais.fdb" ) == target.resolve() finally: firebird_connection.AUTHORIZED_DATABASE_PATH = original def test_validation_rejects_missing_directory_and_alternate_file(tmp_path): from gti_discovery import firebird_connection original = firebird_connection.AUTHORIZED_DATABASE_PATH authorized = tmp_path / "TESTESOFICIAIS.FDB" authorized.write_bytes(b"database") firebird_connection.AUTHORIZED_DATABASE_PATH = authorized try: with pytest.raises(ValueError, match="authorized"): validate_authorized_database_path(tmp_path / "missing.FDB") alternate = tmp_path / "ERP.FDB" alternate.write_bytes(b"database") with pytest.raises(ValueError, match="authorized"): validate_authorized_database_path(alternate) authorized.unlink() with pytest.raises(ValueError, match="regular file"): validate_authorized_database_path(authorized) finally: firebird_connection.AUTHORIZED_DATABASE_PATH = original def test_rejected_path_never_invokes_driver(tmp_path): calls = [] class Driver: def connect(self, **kwargs): calls.append(kwargs) raise AssertionError("driver must not be invoked") with pytest.raises(ValueError): connect_authorized_read_only(tmp_path / "ERP.FDB", Driver()) assert calls == [] def test_connection_requests_and_proves_read_only_mode(tmp_path): target = tmp_path / "TESTESOFICIAIS.FDB" target.write_bytes(b"database") from gti_discovery import firebird_connection original = firebird_connection.AUTHORIZED_DATABASE_PATH firebird_connection.AUTHORIZED_DATABASE_PATH = target calls = [] class DriverConnection: default_tpb = b"\x03\x08\x06\x0f\x11" read_only = True read_only_evidence = { "accepted": True, "isolation_level": "fixture-read-committed-ro", } def execute(self, sql, params=()): return [("TESTESOFICIAIS.FDB",)] class Driver: def connect(self, **kwargs): calls.append(kwargs) return _create_firebird_adapter(DriverConnection(), { "accepted": True, "driver_api": "fdb.Connection.default_tpb", "configured_tpb": b"\x03\x08\x06\x0f\x11", "observed_default_tpb": b"\x03\x08\x06\x0f\x11", }, _ADAPTER_CREATION_TOKEN) try: connection = connect_authorized_read_only(target, Driver(), "fbclient.dll") assert isinstance(connection, FirebirdCatalog) assert connection.read_only is True assert calls == [ { "database": str(target.resolve()), "read_only": True, "client_library": "fbclient.dll", } ] finally: firebird_connection.AUTHORIZED_DATABASE_PATH = original def test_connection_fails_closed_without_proven_read_only_mode(tmp_path): target = tmp_path / "TESTESOFICIAIS.FDB" target.write_bytes(b"database") from gti_discovery import firebird_connection original = firebird_connection.AUTHORIZED_DATABASE_PATH firebird_connection.AUTHORIZED_DATABASE_PATH = target class Driver: def connect(self, **kwargs): return object() try: with pytest.raises(ValueError, match="read-only"): connect_authorized_read_only(target, Driver()) finally: firebird_connection.AUTHORIZED_DATABASE_PATH = original def test_connection_rejects_driver_that_ignores_read_only_setting(tmp_path): target = tmp_path / "TESTESOFICIAIS.FDB" target.write_bytes(b"database") from gti_discovery import firebird_connection original = firebird_connection.AUTHORIZED_DATABASE_PATH firebird_connection.AUTHORIZED_DATABASE_PATH = target class IgnoringConnection: read_only = True def close(self): self.closed = True raw_connection = IgnoringConnection() class Driver: def connect(self, **kwargs): return raw_connection try: with pytest.raises(ValueError, match="read-only"): connect_authorized_read_only(target, Driver()) assert raw_connection.closed is True finally: firebird_connection.AUTHORIZED_DATABASE_PATH = original def test_connection_rejects_lookalike_sealed_adapter_from_untrusted_driver(tmp_path): target = tmp_path / "TESTESOFICIAIS.FDB" target.write_bytes(b"database") from gti_discovery import firebird_connection original = firebird_connection.AUTHORIZED_DATABASE_PATH firebird_connection.AUTHORIZED_DATABASE_PATH = target class Driver: def connect(self, **kwargs): return _FirebirdAdapter(object(), { "accepted": True, "driver_api": "fdb.Connection.default_tpb", "configured_tpb": b"\x03\x08\x06\x0f\x11", "observed_default_tpb": b"\x03\x08\x06\x0f\x11", }) try: with pytest.raises((TypeError, ValueError)): connect_authorized_read_only(target, Driver()) finally: firebird_connection.AUTHORIZED_DATABASE_PATH = original @pytest.mark.parametrize("read_only", [False, None]) def test_connection_closes_raw_connection_without_read_only_proof(tmp_path, read_only): target = tmp_path / "TESTESOFICIAIS.FDB" target.write_bytes(b"database") from gti_discovery import firebird_connection original = firebird_connection.AUTHORIZED_DATABASE_PATH firebird_connection.AUTHORIZED_DATABASE_PATH = target class DriverConnection: def close(self): self.closed = True raw_connection = DriverConnection() if read_only is not None: raw_connection.read_only = read_only raw_connection.closed = False class Driver: def connect(self, **kwargs): return raw_connection try: with pytest.raises(ValueError, match="read-only"): connect_authorized_read_only(target, Driver()) assert raw_connection.closed is True finally: firebird_connection.AUTHORIZED_DATABASE_PATH = original def test_connection_closes_malformed_raw_connection(tmp_path): target = tmp_path / "TESTESOFICIAIS.FDB" target.write_bytes(b"database") from gti_discovery import firebird_connection original = firebird_connection.AUTHORIZED_DATABASE_PATH firebird_connection.AUTHORIZED_DATABASE_PATH = target class DriverConnection: read_only = True def close(self): self.closed = True raw_connection = DriverConnection() raw_connection.closed = False class Driver: def connect(self, **kwargs): return raw_connection try: with pytest.raises(ValueError, match="read-only"): connect_authorized_read_only(target, Driver()) assert raw_connection.closed is True finally: firebird_connection.AUTHORIZED_DATABASE_PATH = original def test_identity_helper_uses_only_database_monitor_query(): from gti_discovery.collector import _CATALOG_QUERIES calls = [] class Adapter: read_only = True def execute(self, sql, params=()): calls.append((sql, params)) return [("TESTESOFICIAIS.FDB",)] _register_approved_adapter(Adapter, _ADAPTER_REGISTRATION_TOKEN) assert get_database_identity(FirebirdCatalog(Adapter())) == "TESTESOFICIAIS.FDB" assert calls == [(_CATALOG_QUERIES["database"], ())] def test_driver_fixture_uses_runtime_fdb_read_only_constant(monkeypatch): import importlib.util script = Path(__file__).parents[1] / "scripts" / "run_firebird_discovery.py" spec = importlib.util.spec_from_file_location("run_firebird_discovery_fixture", script) script_module = importlib.util.module_from_spec(spec) spec.loader.exec_module(script_module) class FdbFixture: ISOLATION_LEVEL_READ_COMMITED_RO = b"\x03\x08\x06\x0f\x11" def connect(self, **kwargs): self.kwargs = kwargs return type("Connection", (), { "default_tpb": kwargs["isolation_level"], "read_only_evidence": { "accepted": True, "isolation_level": kwargs["isolation_level"], } })() fdb = FdbFixture() monkeypatch.setenv("FB_USER", "fixture-user") monkeypatch.setenv("FB_PASSWORD", "fixture-password") driver = script_module._FdbDriver(fdb) driver.connect(database="target.fdb", read_only=True) assert fdb.kwargs["isolation_level"] is fdb.ISOLATION_LEVEL_READ_COMMITED_RO def test_driver_rejects_connection_that_ignores_fdb_read_only_tpb(monkeypatch): import importlib.util script = Path(__file__).parents[1] / "scripts" / "run_firebird_discovery.py" spec = importlib.util.spec_from_file_location("run_firebird_discovery_ignored_tpb", script) script_module = importlib.util.module_from_spec(spec) spec.loader.exec_module(script_module) class FdbFixture: ISOLATION_LEVEL_READ_COMMITED_RO = b"\x03\x08\x06\x0f\x11" def connect(self, **kwargs): self.kwargs = kwargs return type("Connection", (), { "default_tpb": b"ordinary-read-write-tpb", "read_only": True, "read_only_evidence": { "accepted": True, "isolation_level": kwargs["isolation_level"], }, })() monkeypatch.setenv("FB_USER", "fixture-user") monkeypatch.setenv("FB_PASSWORD", "fixture-password") with pytest.raises(RuntimeError, match="read-only"): script_module._FdbDriver(FdbFixture()).connect(database="target.fdb", read_only=True) def test_driver_uses_adapter_configuration_evidence_not_raw_claims(monkeypatch): import importlib.util script = Path(__file__).parents[1] / "scripts" / "run_firebird_discovery.py" spec = importlib.util.spec_from_file_location("run_firebird_discovery_claim", script) script_module = importlib.util.module_from_spec(spec) spec.loader.exec_module(script_module) class FdbFixture: ISOLATION_LEVEL_READ_COMMITED_RO = b"\x03\x08\x06\x0f\x11" def connect(self, **kwargs): return type("Connection", (), { "default_tpb": kwargs["isolation_level"], "read_only": False, "read_only_evidence": {"accepted": True, "isolation_level": kwargs["isolation_level"]}, })() monkeypatch.setenv("FB_USER", "fixture-user") monkeypatch.setenv("FB_PASSWORD", "fixture-password") adapter = script_module._FdbDriver(FdbFixture()).connect(database="target.fdb", read_only=True) assert adapter.read_only_evidence["configured_tpb"] == b"\x03\x08\x06\x0f\x11" assert adapter.read_only_evidence["observed_default_tpb"] == b"\x03\x08\x06\x0f\x11" def test_installed_fdb_runtime_exposes_read_only_isolation_api_without_connecting(): import fdb import importlib.util script = Path(__file__).parents[1] / "scripts" / "run_firebird_discovery.py" spec = importlib.util.spec_from_file_location("run_firebird_discovery_runtime", script) script_module = importlib.util.module_from_spec(spec) spec.loader.exec_module(script_module) assert script_module._read_only_isolation_level(fdb) is getattr( fdb, "ISOLATION_LEVEL_READ_COMMITED_RO" ) def test_identity_mismatch_is_rejected_after_connection(tmp_path, monkeypatch): from gti_discovery import firebird_connection target = tmp_path / "TESTESOFICIAIS.FDB" target.write_bytes(b"database") original = firebird_connection.AUTHORIZED_DATABASE_PATH firebird_connection.AUTHORIZED_DATABASE_PATH = target import importlib.util script = Path(__file__).parents[1] / "scripts" / "run_firebird_discovery.py" spec = importlib.util.spec_from_file_location("run_firebird_discovery_identity", script) script_module = importlib.util.module_from_spec(spec) spec.loader.exec_module(script_module) monkeypatch.setenv("FB_USER", "fixture-user") monkeypatch.setenv("FB_PASSWORD", "fixture-password") monkeypatch.setattr(script_module, "_client_metadata", lambda path: { "path": str(path), "exists": True, "version": "2.5.9.27139" }) monkeypatch.setattr(script_module, "_security_gate", lambda path, driver: { "path": str(path), "exists": True, "version": "2.5.9.27139" }) class RawConnection: default_tpb = b"\x03\x08\x06\x0f\x11" read_only = True read_only_evidence = { "accepted": True, "isolation_level": "fixture-read-committed-ro", } def execute(self, sql, params=()): return [("OTHER.FDB",)] def close(self): pass _register_approved_adapter(RawConnection, _ADAPTER_REGISTRATION_TOKEN) class Driver: version = "test-driver" def compatibility_evidence(self, client_version): return { "client_version": client_version, "fdb_version": "2.0.4", "firebird_version": "2.5.9", "read_only_isolation": True, "read_only_api": "fdb.Connection.default_tpb", "read_only_tpb": b"\x03\x08\x06\x0f\x11", } def connect(self, **kwargs): return _create_firebird_adapter(RawConnection(), { "accepted": True, "driver_api": "fdb.Connection.default_tpb", "configured_tpb": b"\x03\x08\x06\x0f\x11", "observed_default_tpb": b"\x03\x08\x06\x0f\x11", }, _ADAPTER_CREATION_TOKEN) try: result = script_module.run_discovery(target, driver=Driver()) assert result["status"] == "MISSION_00_BLOCKED" assert result["blocker"] == "identity_mismatch" assert result["connection_attempts"] == 1 assert result["other_databases_accessed"] == "UNKNOWN" assert result["application_writes"] == 0 finally: firebird_connection.AUTHORIZED_DATABASE_PATH = original