"""Migration rehearsal evidence validation. This module does not create databases, restore backups or execute migrations. It validates supplied evidence. """ import copy import re import uuid from datetime import timedelta from core.approval import ( ApprovalError, CONTEXT_FIELDS, validate_context, timestamp, parse_timestamp, ) from core.compatibility import canonical_hash class RehearsalError(RuntimeError): """Invalid or insufficient migration rehearsal evidence.""" BASE_FIELDS = CONTEXT_FIELDS - { "rehearsal_fingerprint", } EXECUTION_FIELDS = { "driver", "source_database", "target_database", "target_identity", "applied_migrations", "checks", } CHECK_FIELDS = { "isolation_verified", "backup_restored", "migration_succeeded", "migration_history_verified", "application_verified", "cleanup_verified", } RECORD_FIELDS = { "format_version", "rehearsal_id", "context", "execution", "completed_at", "fingerprint", } def require(condition, message): if not condition: raise RehearsalError(message) def matches(value, pattern): return ( isinstance(value, str) and re.fullmatch(pattern, value) is not None ) def validate_base_context(context): require( isinstance(context, dict) and set(context) == BASE_FIELDS, "Invalid rehearsal context", ) try: validate_context({ **context, "rehearsal_fingerprint": "0" * 64, }) except ApprovalError: raise RehearsalError( "Invalid rehearsal approval context" ) from None def validate_execution(context, execution): require( isinstance(execution, dict) and set(execution) == EXECUTION_FIELDS, "Invalid rehearsal execution evidence", ) require( execution["driver"] in ( "mysql", "postgresql", ), "Unsupported rehearsal database driver", ) source = execution["source_database"] target = execution["target_database"] require( matches(source, r"[A-Za-z_][A-Za-z0-9_]{0,62}"), "Invalid source database", ) require( matches( target, r"isolated_restore_[a-z0-9_]{1,45}", ), "Invalid isolated database name", ) require( source.lower() != target.lower(), "Rehearsal must not target the source database", ) require( matches( execution["target_identity"], r"[a-f0-9]{64}", ), "Invalid rehearsal database identity", ) require( execution["target_identity"] != context["database_identity"], "Rehearsal database identity matches source", ) require( isinstance(execution["applied_migrations"], list) and execution["applied_migrations"] == context["pending_migrations"], "Applied migrations differ from approved inventory", ) checks = execution["checks"] require( isinstance(checks, dict) and set(checks) == CHECK_FIELDS, "Incomplete rehearsal verification checks", ) for name, status in checks.items(): require( status is True, f"Rehearsal check failed: {name}", ) def fingerprint(record): return canonical_hash({ key: value for key, value in record.items() if key != "fingerprint" }) def create_rehearsal( context, execution, *, completed_at, ): validate_base_context(context) validate_execution( context, execution, ) try: completed = timestamp(completed_at) except ApprovalError: raise RehearsalError( "Invalid rehearsal completion timestamp" ) from None record = { "format_version": 1, "rehearsal_id": uuid.uuid4().hex, "context": copy.deepcopy(context), "execution": copy.deepcopy(execution), "completed_at": completed.isoformat(), } record["fingerprint"] = fingerprint(record) return record def verify_rehearsal( record, context, *, now, ): validate_base_context(context) require( isinstance(record, dict) and set(record) == RECORD_FIELDS, "Invalid rehearsal record", ) require( type(record["format_version"]) is int and record["format_version"] == 1, "Unsupported rehearsal format", ) require( matches( record["rehearsal_id"], r"[a-f0-9]{32}", ), "Invalid rehearsal identifier", ) validate_base_context(record["context"]) require( record["context"] == context, "Rehearsal context changed", ) validate_execution( context, record["execution"], ) require( matches( record["fingerprint"], r"[a-f0-9]{64}", ) and fingerprint(record) == record["fingerprint"], "Rehearsal fingerprint mismatch", ) try: completed = parse_timestamp( record["completed_at"] ) current = timestamp(now) except ApprovalError: raise RehearsalError( "Invalid rehearsal timestamp" ) from None require( timedelta(0) <= current - completed < timedelta(hours=24), "Rehearsal expired or not yet valid", ) return True def approval_context(record, context, *, now): verify_rehearsal( record, context, now=now, ) result = copy.deepcopy(context) result["rehearsal_fingerprint"] = ( record["fingerprint"] ) return result