diff --git a/CHANGELOG.md b/CHANGELOG.md index e711d20..7c2352b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -30,6 +30,8 @@ ## Терминал владельца +- `restores inspect-region` проверяет участок верхнего мира DJ2 по выбранному + холодному бэкапу. В отчёте видны границы, объём, покрытие чанков и хеш снимка. - `action-history` ищет серверные действия DJ2 по координатам, периоду и UUID. Поиск показывает качество покрытия, а материалы инцидента можно сохранить с собственной проверенной копией мира. diff --git a/docs/ADMIN.md b/docs/ADMIN.md index 7a07771..a12e3c9 100644 --- a/docs/ADMIN.md +++ b/docs/ADMIN.md @@ -138,6 +138,9 @@ volume runtime**: пересоздание контейнера сохраняе Можно сохранить отдельный комплект с журналом, диагностикой и проверенной копией мира. [Журнал действий DJ2](ACTION_ATTRIBUTION.md). +`restores inspect-region` проверяет участок верхнего мира остановленного DJ2 +по выбранному холодному бэкапу. [Команда и требования](REGION_RECOVERY.md#проверка-участка-перед-восстановлением). + ```powershell uv run omk admin --config .omk-admin/operator.toml diagnostics dj2 ``` diff --git a/docs/REGION_RECOVERY.md b/docs/REGION_RECOVERY.md index 74fd565..3d926f5 100644 --- a/docs/REGION_RECOVERY.md +++ b/docs/REGION_RECOVERY.md @@ -8,6 +8,31 @@ FTB Backups 1.1.0.1 и автоматическая политика хране Практический список команд — [commands/dj2/RECOVERY.md](commands/dj2/RECOVERY.md), запуск нового стенда — [commands/dj2/TESTING.md](commands/dj2/TESTING.md). +## Проверка участка перед восстановлением + +Для DJ2 можно сверить выделение в верхнем мире с управляемым холодным +бэкапом. Команда использует существующую настройку +[`backups.toml`](../deploy/owner/backups.example.toml) и ожидает штатно +остановленный источник. Идентификатор снимка берётся из `backups list --server dj2`. + +```text +uv run omk admin --config .omk-admin/operator.toml restores inspect-region --server dj2 --snapshot SNAPSHOT_ID --minimum 130 241 130 --maximum 135 243 134 +``` + +Обе точки включаются в участок. Укажите меньшую координату по каждой оси +в `--minimum`. Допустимы высоты от 0 до 255 и до 64 чанков внутри сохранённой +границы мира. + +Команда проверяет SHA-256 архива и наличие всех чанков в обоих сохранениях. +Имя мира, сид и параметры генератора должны совпасть. Формат сохранений, +версии модов и реестры Forge сверяются по `level.dat`. В ответе остаются +границы, объём участка, идентификатор и хеш снимка. Хеши текущего `level.dat` +и выбранных чанков позволяют опознать сохранение, которое участвовало в проверке. + +Мир и хранилище бэкапов подключаются к проверке только для чтения. Для +будущего применения отдельно нужны свежая копия, подтверждение владельца +и проверка результата на подготовленном томе. + ## Требуемое поведение Администратор выбирает сервер/измерение, трёхмерную область и доступный снимок до грифа. diff --git a/omk/owner/admin_restores.py b/omk/owner/admin_restores.py index 38b1bc7..1e592c9 100644 --- a/omk/owner/admin_restores.py +++ b/omk/owner/admin_restores.py @@ -26,7 +26,7 @@ from omk.owner.panels import owner_volumes from omk.shared.nbt import MAX_BYTES from omk.shared.profiles import PROJECT_ROOT -from omk.worlds import incident_players, incident_recovery +from omk.worlds import incident_players, incident_recovery, region_restore_inspection def target_for(config, server, source): @@ -38,7 +38,7 @@ def destination(target, *, unused=False): def worker(record, action, *, evidence_sha256=None): - source, target, settings = record["source"], record["target"], record["settings"] + source, settings = record["source"], record["settings"] request = { "action": action, "operation": record["operation"], @@ -50,6 +50,8 @@ def worker(record, action, *, evidence_sha256=None): for k in ("max_bytes", "max_count", "staging_bytes", "reserve_bytes") }, } + if action == "inspect-region": + request.update(record["selection"]) if "expected" in record: request["expected"] = record["expected"] if "incident" in record: @@ -84,11 +86,15 @@ def worker(record, action, *, evidence_sha256=None): "--mount", f"type=volume,source={source['data_volume']},target=/current,readonly", "--mount", - f"type=volume,source={target['data_volume']},target=/restore" - + ("" if action == "apply" else ",readonly"), - "--mount", f"type=bind,source={PROJECT_ROOT / 'omk'},target=/src/omk,readonly", ] + if action != "inspect-region": + target = record["target"] + mode = "" if action == "apply" else ",readonly" + args += [ + "--mount", + f"type=volume,source={target['data_volume']},target=/restore{mode}", + ] if action == "evidence": args += ["--log-driver", "none"] for filename in ("__init__.py", "nbt.py"): @@ -115,6 +121,13 @@ def worker(record, action, *, evidence_sha256=None): raise AdminError("Restore worker response exceeds limit") result = json.loads(text) if result.get("ok") is not True or not isinstance(result.get("result"), dict): + reason = result.get("region_reason") + if ( + action == "inspect-region" + and isinstance(reason, str) + and reason in region_restore_inspection.REASONS + ): + raise AdminError(region_restore_inspection.REASONS[reason]) kind = result.get("error_type", "InvalidResponse") if not isinstance(kind, str) or not re.fullmatch(r"[A-Za-z]{1,64}", kind): kind = "InvalidResponse" @@ -367,6 +380,35 @@ def run(config, operation, *, verify=False, environment=None): return {"ok": True, "operation": operation, "stage": "staged", **result} +def inspect_region(config, server, snapshot, minimum, maximum): + """Run a read-only check against a selected backup and the stopped source.""" + from omk.worlds.world_cutover import require_clear # noqa: PLC0415 + + if not isinstance(snapshot, str) or not re.fullmatch( + r"snapshot-[a-f0-9]{32}", snapshot + ): + raise AdminError("Invalid selected restore snapshot") + with backups.locked(config): + require_clear(config, server) + source = backups.target_for(config, server) + backups.local_engine() + checkpoint = backups.checkpoint(source) + record = { + "operation": uuid4().hex, + "source": source, + "settings": backups.settings(), + "snapshot": snapshot, + "selection": {"minimum": minimum, "maximum": maximum}, + } + result = worker(record, "inspect-region") + if ( + backups.target_for(config, server) != source + or backups.checkpoint(source) != checkpoint + ): + raise AdminError("Stopped source changed during region inspection") + return {"ok": True, "server": server, **result} + + def add_restore_parser(actions): parser = actions.add_parser( "restores", help="Owner Linux restore staging; no lifecycle or promotion" @@ -379,11 +421,24 @@ def add_restore_parser(actions): "--incident", help="Private JSON selection for a single-player rescue or object quarantine", ) + inspection = sub.add_parser( + "inspect-region", help="Check a historical overworld selection without changes" + ) + inspection.add_argument("--server", required=True) + inspection.add_argument("--snapshot", required=True) + for flag in ("--minimum", "--maximum"): + inspection.add_argument( + flag, type=int, nargs=3, metavar=("X", "Y", "Z"), required=True + ) for action in ("apply", "verify", "status"): sub.add_parser(action).add_argument("--operation", required=True) def run_restores(config, args): + if args.restore_action == "inspect-region": + return inspect_region( + config, args.server, args.snapshot, args.minimum, args.maximum + ) if args.restore_action == "plan": path = getattr(args, "incident", None) incident = ( diff --git a/omk/worlds/forge112_regions.py b/omk/worlds/forge112_regions.py index 74f4cd5..8715369 100644 --- a/omk/worlds/forge112_regions.py +++ b/omk/worlds/forge112_regions.py @@ -83,6 +83,57 @@ def apply(self, path): os.fsync(target.fileno()) +def read_region_locations(source, size): + """Check the Anvil sector table of a bounded seekable region stream.""" + if not 2 * SECTOR <= size <= 1024**3 or size % SECTOR: + raise ValueError("Unsupported region size") + header = source.read(SECTOR) + if len(header) != SECTOR: + raise ValueError("Truncated region location table") + locations = {} + occupied = {0, 1} + for index in range(1024): + offset = int.from_bytes(header[index * 4 : index * 4 + 3], "big") + count = header[index * 4 + 3] + if offset == count == 0: + continue + sectors = set(range(offset, offset + count)) + if ( + offset < 2 + or not count + or (offset + count) * SECTOR > size + or occupied & sectors + ): + raise ValueError("Invalid or overlapping region allocation") + occupied.update(sectors) + locations[index] = offset, count + return locations + + +def read_chunk_record(source, location, coordinates): + """Read and check one Anvil chunk from a region file or a ZIP entry.""" + offset, count = location + source.seek(offset * SECTOR) + header = source.read(5) + if len(header) != 5: + raise ValueError("Truncated chunk header") + length, codec = struct.unpack(">IB", header) + if codec != 2 or not 1 < length <= count * SECTOR - 4: + raise ValueError("Unsupported chunk compression") + compressed = source.read(length - 1) + if len(compressed) != length - 1: + raise ValueError("Truncated compressed chunk") + inflater = zlib.decompressobj() + raw = inflater.decompress(compressed, MAX_BYTES + 1) + if len(raw) > MAX_BYTES or not inflater.eof or inflater.unused_data: + raise ValueError("Invalid or oversized chunk NBT") + name, root = read_nbt(raw) + level = value(root, "Level", 10) + if (value(level, "xPos", 3), value(level, "zPos", 3)) != coordinates: + raise ValueError("Chunk coordinates differ from region entry") + return name, root, raw + + class Region: """Read chunks from one Minecraft 1.12 Anvil region file.""" @@ -95,27 +146,8 @@ def __init__(self, path: Path, world: Path): self.path = path self.x, self.z = map(int, match.groups()) self.size = path.stat().st_size - if not 2 * SECTOR <= self.size <= 1024**3 or self.size % SECTOR: - raise ValueError("Unsupported region size") with path.open("rb") as source: - header = source.read(SECTOR) - self.locations = {} - occupied = {0, 1} - for index in range(1024): - offset = int.from_bytes(header[index * 4 : index * 4 + 3], "big") - count = header[index * 4 + 3] - if offset == count == 0: - continue - sectors = set(range(offset, offset + count)) - if ( - offset < 2 - or not count - or (offset + count) * SECTOR > self.size - or occupied & sectors - ): - raise ValueError("Invalid or overlapping region allocation") - occupied.update(sectors) - self.locations[index] = offset, count + self.locations = read_region_locations(source, self.size) def chunk(self, index): """Decode the stored chunk at the requested region coordinates.""" @@ -125,28 +157,9 @@ def record(self, index): """Read the complete chunk record and its original uncompressed bytes.""" if index not in self.locations: raise ValueError("Landing chunk is not saved") - offset, count = self.locations[index] + coordinates = self.x * 32 + index % 32, self.z * 32 + index // 32 with self.path.open("rb") as source: - source.seek(offset * SECTOR) - header = source.read(5) - if len(header) != 5: - raise ValueError("Truncated chunk header") - length, codec = struct.unpack(">IB", header) - if codec != 2 or not 1 < length <= count * SECTOR - 4: - raise ValueError("Unsupported chunk compression") - compressed = source.read(length - 1) - if len(compressed) != length - 1: - raise ValueError("Truncated compressed chunk") - inflater = zlib.decompressobj() - raw = inflater.decompress(compressed, MAX_BYTES + 1) - if len(raw) > MAX_BYTES or not inflater.eof or inflater.unused_data: - raise ValueError("Invalid or oversized chunk NBT") - name, root = read_nbt(raw) - level = value(root, "Level", 10) - expected = self.x * 32 + index % 32, self.z * 32 + index // 32 - if (value(level, "xPos", 3), value(level, "zPos", 3)) != expected: - raise ValueError("Chunk coordinates differ from region entry") - return name, root, raw + return read_chunk_record(source, self.locations[index], coordinates) def replacement(self, index, name, root): """Encode a verified chunk inside its current allocation.""" diff --git a/omk/worlds/owner_restore_worker.py b/omk/worlds/owner_restore_worker.py index e8d78ad..dd33490 100644 --- a/omk/worlds/owner_restore_worker.py +++ b/omk/worlds/owner_restore_worker.py @@ -23,6 +23,7 @@ incident_recovery, linux_restore_policy as policy, linux_world_restore as raw, + region_restore_inspection, ) PLAN = ".omk-owner-restore-plan.json" @@ -211,6 +212,8 @@ def execute( ): if sys.platform != "linux": raise ValueError("Owner world restore requires Linux") + if request.get("action") == "inspect-region": + return region_restore_inspection.inspect(request, storage, current) functions = {"plan": plan, "apply": apply, "verify": verify} if "incident" in request: return incident_recovery.execute(request, storage, target, current) @@ -227,5 +230,8 @@ def execute( result = execute(json.loads(data)) print(json.dumps({"ok": True, "result": result})) except Exception as error: - print(json.dumps({"ok": False, "error_type": type(error).__name__})) + report = {"ok": False, "error_type": type(error).__name__} + if isinstance(error, region_restore_inspection.InspectionRefused): + report["region_reason"] = error.reason + print(json.dumps(report)) raise SystemExit(1) from None diff --git a/omk/worlds/region_restore_inspection.py b/omk/worlds/region_restore_inspection.py new file mode 100644 index 0000000..668c7d8 --- /dev/null +++ b/omk/worlds/region_restore_inspection.py @@ -0,0 +1,217 @@ +"""Check a selected Forge 1.12.2 overworld area against a verified cold backup.""" + +import hashlib +import math +import re +import zipfile +import zlib +from pathlib import Path + +from omk.backups.backup_archive import regular_file +from omk.backups.backup_store import BackupPolicy, BackupStore, _directory +from omk.backups.ftb_restore_authority import nbt +from omk.shared.nbt import MAX_BYTES +from omk.worlds import forge112_regions as anvil + +MAX_CHUNKS = 64 +MAX_COORDINATE = 29_999_983 + +REASONS = { + "selection": "Use ordered integer coordinates inside the world and up to 64 chunks", + "snapshot": "The selected verified cold backup is unavailable", + "world": "The backup and stopped save differ in world name, seed or generator", + "format": "The saves differ in Forge format, saved mods or registry, or have unreadable level data", + "border": "The selected area must fit within a stationary saved world border", + "coverage": "The selected chunks must be present and readable in both saves", +} + + +class InspectionRefused(ValueError): + """The selected area failed one of the read-only restore checks.""" + + def __init__(self, reason): + self.reason = reason + super().__init__(REASONS[reason]) + + +def _selection(minimum, maximum): + if any( + not isinstance(point, (list, tuple)) + or len(point) != 3 + or any(type(coordinate) is not int for coordinate in point) + for point in (minimum, maximum) + ): + raise InspectionRefused("selection") + if ( + any(lower > upper for lower, upper in zip(minimum, maximum, strict=True)) + or not 0 <= minimum[1] <= maximum[1] <= 255 + or any( + abs(point[axis]) > MAX_COORDINATE + for point in (minimum, maximum) + for axis in (0, 2) + ) + ): + raise InspectionRefused("selection") + first_x, last_x = minimum[0] // 16, maximum[0] // 16 + first_z, last_z = minimum[2] // 16, maximum[2] // 16 + chunks = (last_x - first_x + 1) * (last_z - first_z + 1) + if chunks > MAX_CHUNKS: + raise InspectionRefused("selection") + regions = {} + for chunk_z in range(first_z, last_z + 1): + for chunk_x in range(first_x, last_x + 1): + region = chunk_x // 32, chunk_z // 32 + index = chunk_x % 32 + (chunk_z % 32) * 32 + regions.setdefault(region, {})[index] = (chunk_x, chunk_z) + blocks = math.prod( + upper - lower + 1 for lower, upper in zip(minimum, maximum, strict=True) + ) + return regions, blocks, chunks + + +def _level(raw): + root = nbt(raw) + data = anvil.value(root, "Data", 10) + if anvil.value(data, "DataVersion", 3) != anvil.DATA_VERSION: + raise ValueError("Unreviewed level version") + identity = tuple( + anvil.value(data, field, kind) + for field, kind in ( + ("RandomSeed", 4), + ("LevelName", 8), + ("generatorName", 8), + ("generatorVersion", 3), + ("generatorOptions", 8), + ) + ) + fml = anvil.value(root, "FML", 10) + rows = anvil.compounds(fml, "ModList") + mods = { + anvil.value(row, "ModId", 8): anvil.value(row, "ModVersion", 8) for row in rows + } + if len(mods) != len(rows) or not mods: + raise ValueError("Ambiguous saved mods") + anvil.block_registry(root) + return data, identity, mods, anvil.value(fml, "Registries", 10) + + +def _check_levels(archive, world, minimum, maximum): + file = world / "level.dat" + try: + if ( + regular_file(file) > MAX_BYTES + or archive.getinfo(f"{world.name}/level.dat").file_size > MAX_BYTES + ): + raise ValueError("Oversized level data") + saved = archive.read(f"{world.name}/level.dat") + with file.open("rb") as stream: + current = stream.read(MAX_BYTES + 1) + _, saved_identity, saved_mods, saved_registry = _level(saved) + data, identity, mods, registry = _level(current) + except OSError, ValueError, KeyError, zipfile.BadZipFile, zlib.error: + raise InspectionRefused("format") from None + if identity != saved_identity: + raise InspectionRefused("world") + if mods != saved_mods or registry != saved_registry: + raise InspectionRefused("format") + try: + x, z, size = ( + anvil.value(data, key, 6) + for key in ("BorderCenterX", "BorderCenterZ", "BorderSize") + ) + lerp = anvil.value(data, "BorderSizeLerpTime", 4) + except ValueError: + raise InspectionRefused("border") from None + if ( + lerp != 0 + or not all(math.isfinite(v) for v in (x, z, size)) + or not 1 <= size <= 60_000_000 + or any( + minimum[axis] < center - size / 2 or maximum[axis] + 1 > center + size / 2 + for axis, center in ((0, x), (2, z)) + ) + ): + raise InspectionRefused("border") + return hashlib.sha256(current).hexdigest(), len(mods) + + +def _check_chunk(record): + name, root, raw = record + anvil.check_editable(name, root, raw) + level = anvil.value(root, "Level", 10) + anvil.sections(level) + for field in ("TileEntities", "Entities"): + anvil.compounds(level, field) + return raw + + +def _check_coverage(archive, world, regions): + current_chunks = hashlib.sha256() + try: + for (region_x, region_z), chunks in regions.items(): + relative = f"region/r.{region_x}.{region_z}.mca" + entry = archive.getinfo(f"{world.name}/{relative}") + local = anvil.Region(world / relative, world) + with archive.open(entry) as incoming: + historical = anvil.read_region_locations(incoming, entry.file_size) + if ( + not chunks.keys() <= historical.keys() + or not chunks.keys() <= local.locations.keys() + ): + raise InspectionRefused("coverage") + for index in sorted(chunks, key=lambda index: historical[index][0]): + _check_chunk( + anvil.read_chunk_record( + incoming, historical[index], chunks[index] + ) + ) + raw = _check_chunk(local.record(index)) + current_chunks.update(hashlib.sha256(raw).digest()) + except OSError, ValueError, KeyError, zipfile.BadZipFile, zlib.error: + raise InspectionRefused("coverage") from None + return current_chunks.hexdigest() + + +def inspect(request, storage: Path, current: Path): + """Compare a selected backup with a stopped save without writing either input.""" + minimum, maximum = request["minimum"], request["maximum"] + regions, blocks, chunks = _selection(minimum, maximum) + name = request["world"] + if not isinstance(name, str) or not re.fullmatch(r"[A-Za-z0-9_-]{1,64}", name): + raise InspectionRefused("world") + world = current / name + try: + _directory(world) + _directory(storage) + if current.samefile(storage) or {entry.name for entry in storage.iterdir()} != { + "store" + }: + raise ValueError("Invalid backup storage") + store = BackupStore( + storage / "store", + BackupPolicy(**request["policy"]), + max_expanded_bytes=request["world_max_bytes"], + path_policy="linux-server", + ) + snapshot, manifest = store.readonly_snapshot(request["snapshot"]) + except OSError, ValueError, KeyError, TypeError, zipfile.BadZipFile, zlib.error: + raise InspectionRefused("snapshot") from None + if not all(path.startswith(name + "/") for path in manifest["files"]): + raise InspectionRefused("world") + with zipfile.ZipFile(snapshot) as archive: + level_hash, mods = _check_levels(archive, world, minimum, maximum) + chunks_hash = _check_coverage(archive, world, regions) + return { + "world": name, + "dimension": 0, + "minimum": list(minimum), + "maximum": list(maximum), + "blocks": blocks, + "chunks": chunks, + "data_version": anvil.DATA_VERSION, + "saved_mods": mods, + "snapshot": request["snapshot"], + "archive_sha256": manifest["sha256"], + "current_level_sha256": level_hash, + "current_chunks_sha256": chunks_hash, + } diff --git a/tests/fixtures/unit/worlds/region_restore_inspection.py b/tests/fixtures/unit/worlds/region_restore_inspection.py new file mode 100644 index 0000000..1a9b0df --- /dev/null +++ b/tests/fixtures/unit/worlds/region_restore_inspection.py @@ -0,0 +1,85 @@ +"""Archives and saved regions for the offline selection check.""" + +import zipfile + +import pytest + +from omk.backups.backup_store import BackupPolicy, BackupStore +from omk.backups.stopped_world_backup import inventory +from omk.shared.nbt import Tag +from tests.fixtures.unit.worlds.incident_recovery import chunk, compounds, region +from tests.fixtures.unit.worlds.resource_reset_inventory import encoded + +POLICY = BackupPolicy(64 * 1024**2, 3, 32 * 1024**2, 1) + + +def write_level(world, *, seed=123, version=1343, mod_version="2.23.4", border=1024.0): + level = { + "Data": Tag( + 10, + { + "DataVersion": Tag(3, version), + "RandomSeed": Tag(4, seed), + "LevelName": Tag(8, world.name), + "generatorName": Tag(8, "default"), + "generatorVersion": Tag(3, 1), + "generatorOptions": Tag(8, ""), + "BorderCenterX": Tag(6, 0.0), + "BorderCenterZ": Tag(6, 0.0), + "BorderSize": Tag(6, border), + "BorderSizeLerpTime": Tag(4, 0), + }, + ), + "FML": Tag( + 10, + { + "ModList": compounds( + {"ModId": Tag(8, "fixture"), "ModVersion": Tag(8, mod_version)} + ), + "Registries": Tag( + 10, + { + "minecraft:blocks": Tag( + 10, + { + "ids": compounds( + {"V": Tag(3, 0), "K": Tag(8, "minecraft:air")} + ) + }, + ) + }, + ), + }, + ), + } + encoded(world / "level.dat", level) + + +@pytest.fixture +def region_inputs(tmp_path): + historical = tmp_path / "historical" / "world" + current = tmp_path / "current" / "world" + for world in (historical, current): + region(world / "region/r.-1.0.mca", chunk(-2, 0), chunk(-1, 0)) + # The same region coordinates in another dimension contain a different chunk. + region(world / "DIM-1/region/r.-1.0.mca", chunk(-3, 0)) + write_level(world) + storage = tmp_path / "backups" + storage.mkdir() + store = BackupStore.create(storage / "store", POLICY, path_policy="linux-server") + archive = tmp_path / "archive.zip" + files = inventory(historical, world_name="world", path_policy="linux-server") + with zipfile.ZipFile(archive, "w") as output: + for name in sorted(files): + output.write(historical.parent / name, name) + snapshot = store.publish(archive, files) + request = { + "action": "inspect-region", + "world": "world", + "snapshot": snapshot["id"], + "minimum": [-17, 80, 4], + "maximum": [-16, 83, 6], + "world_max_bytes": 32 * 1024**2, + "policy": vars(POLICY), + } + return request, storage, current, store.root / snapshot["id"] / "archive.zip" diff --git a/tests/unit/worlds/test_region_restore_inspection.py b/tests/unit/worlds/test_region_restore_inspection.py new file mode 100644 index 0000000..9f25092 --- /dev/null +++ b/tests/unit/worlds/test_region_restore_inspection.py @@ -0,0 +1,74 @@ +import hashlib + +import pytest + +from omk.backups.stopped_world_backup import inventory +from omk.worlds.region_restore_inspection import InspectionRefused, inspect +from tests.fixtures.unit.worlds.region_restore_inspection import ( + region_inputs, + write_level, +) + +__all__ = ["region_inputs"] + + +def test_checks_multichunk_selection_and_source_hashes_without_writing(region_inputs): + request, storage, current, snapshot = region_inputs + before = inventory(current, world_name="world", path_policy="linux-server") + archive_hash = hashlib.sha256(snapshot.read_bytes()).hexdigest() + result = inspect(request, storage, current.parent) + assert result["dimension"] == 0 and result["data_version"] == 1343 + assert result["minimum"] == [-17, 80, 4] and result["maximum"] == [-16, 83, 6] + assert result["chunks"] == 2 and result["blocks"] == 24 + assert result["archive_sha256"] == archive_hash + assert result["current_level_sha256"] == before["world/level.dat"]["sha256"] + assert len(result["current_chunks_sha256"]) == 64 + assert inspect(request, storage, current.parent) == result + assert inventory(current, world_name="world", path_policy="linux-server") == before + assert hashlib.sha256(snapshot.read_bytes()).hexdigest() == archive_hash + + +@pytest.mark.parametrize( + ("level_changes", "expected"), + [ + ({"seed": 124}, "world"), + ({"version": 1344}, "format"), + ({"mod_version": "2.23.5"}, "format"), + ({"border": 30.0}, "border"), + ], +) +def test_refuses_different_world_format_or_border( + region_inputs, level_changes, expected +): + request, storage, current, _ = region_inputs + write_level(current, **level_changes) + with pytest.raises(InspectionRefused) as error: + inspect(request, storage, current.parent) + assert error.value.reason == expected + + +def test_refuses_missing_overworld_chunk_even_when_nether_has_it(region_inputs): + request, storage, current, _ = region_inputs + request.update(minimum=[-33, 80, 4], maximum=[-33, 83, 6]) + with pytest.raises(InspectionRefused) as error: + inspect(request, storage, current.parent) + assert error.value.reason == "coverage" + + +def test_rejects_archive_changed_after_it_was_verified(region_inputs): + request, storage, current, snapshot = region_inputs + data = bytearray(snapshot.read_bytes()) + data[-1] ^= 1 + snapshot.write_bytes(data) + with pytest.raises(InspectionRefused) as error: + inspect(request, storage, current.parent) + assert error.value.reason == "snapshot" + + +@pytest.mark.parametrize("maximum", [[-18, 83, 6], [-16, 256, 6], [1040, 83, 6]]) +def test_refuses_reversed_excessive_or_oversized_selection(region_inputs, maximum): + request, storage, current, _ = region_inputs + request["maximum"] = maximum + with pytest.raises(InspectionRefused) as error: + inspect(request, storage, current.parent) + assert error.value.reason == "selection"