diff --git a/doc/file_format.md b/doc/file_format.md index db5d9ee..7bf699c 100644 --- a/doc/file_format.md +++ b/doc/file_format.md @@ -141,8 +141,8 @@ data_block_meta[data_block_count] | 11 | 8 + 8n | `file_offsets` | `u64 count` + `count × u64`, relative to the block payload | | 12 | 8 + 8n | `file_hashes` | `u64 count` + `count × u64`, XXH64 of the original bytes | -The raw `u64` arrays are stored as consecutive little-endian values. A data block meta is at least -12 × 8 = 96 bytes. +The raw `u64` arrays are stored as consecutive little-endian values. Empty data blocks are invalid; the +smallest valid block contains one file and is 137 bytes. ### magic_number @@ -166,8 +166,9 @@ The reader rejects archives that violate these cross-field invariants; a writer - For `kLZ4`/`kLZ4HC`, `file_orig_sizes` and `file_compressed_sizes` fit the LZ4 `int` API, `file_orig_sizes <= 255 * file_compressed_sizes`, and a zero original size requires a zero stored size. - Every `file_ids[i]` exists in `file_entry_records`; the entry's `block_id`, `file_orig_size`, `file_compressed_size` and absolute `file_offset` agree with the block, and every indexed file is referenced exactly once. - Directory paths are unique, and a directory contains no duplicate file names, so every extracted file has a distinct output path. +- The directory index must form a tree rooted at `kRootDirId` (1): every non-root directory appears exactly once as a child, no directory is its own ancestor, and every directory is reachable from the root. The rendering commands (`tree`, `ls`, `dump`) additionally reject trees deeper than 128 to bound their recursion; `unpack` and `stat` do not apply that limit. - `unpack` enforces a per-file decompressed-size budget (`--max-decompressed-size`, default 1 GiB, `0` disables it). Archives with larger files need a larger budget or chunked files (#38). -- All archive readers enforce a per-archive metadata budget (`--max-metadata-size`, default 1 GiB, `0` disables it) for both the stored and the uncompressed metadata before allocating either. Compressed metadata above the LZ4 `int` limit is always rejected, compressed metadata must be strictly smaller than its original size, and empty data blocks are invalid. +- All archive readers enforce a per-archive metadata budget (`--max-metadata-size`, default 1 GiB, `0` disables it) for both the stored and the uncompressed metadata before allocating either. Compressed metadata above the LZ4 `int` limit is always rejected, and compressed metadata must be strictly smaller than its original size. ### version encoding and compatibility diff --git a/doc/file_format_CN.md b/doc/file_format_CN.md index fc04041..c827c84 100644 --- a/doc/file_format_CN.md +++ b/doc/file_format_CN.md @@ -140,7 +140,7 @@ data_block_meta[data_block_count] | 11 | 8 + 8n | `file_offsets` | `u64 count` + `count × u64`,相对于块 payload 起点 | | 12 | 8 + 8n | `file_hashes` | `u64 count` + `count × u64`,原始数据的 XXH64 | -原始 `u64` 数组按连续的小端数值存储。一个 data block meta 至少为 12 × 8 = 96 字节。 +原始 `u64` 数组按连续的小端数值存储。空 data block 是非法的;最小的合法块包含一个文件,共 137 字节。 ### magic_number @@ -164,8 +164,9 @@ data_block_meta[data_block_count] - 对 `kLZ4`/`kLZ4HC`,`file_orig_sizes` 和 `file_compressed_sizes` 必须落在 LZ4 的 `int` API 范围内,`file_orig_sizes <= 255 * file_compressed_sizes`,且原始大小为 0 时存储大小也必须为 0。 - 每个 `file_ids[i]` 都必须存在于 `file_entry_records`,其 `block_id`、`file_orig_size`、`file_compressed_size` 和绝对 `file_offset` 与块元数据一致;所有索引文件都必须被且仅被引用一次。 - 目录路径唯一,同一目录内文件名唯一,保证每个解压文件有唯一的输出路径。 +- 目录索引必须是以 `kRootDirId`(1)为根的树:每个非 root 目录恰好出现一次作为子节点,任何目录都不是自己的祖先,所有目录都能从 root 到达。渲染命令(`tree`、`ls`、`dump`)额外拒绝深度超过 128 的树以限制递归;`unpack` 和 `stat` 不施加该限制。空 data block 是非法的。 - `unpack` 对每个文件施加解压大小预算(`--max-decompressed-size`,默认 1 GiB,`0` 表示不限制)。更大的文件需要调大预算,或等待分块支持(#38)。 -- 所有归档读取命令都对存储和未压缩 metadata 施加每归档预算(`--max-metadata-size`,默认 1 GiB,`0` 表示不限制),并在分配任一缓冲区之前检查。超过 LZ4 `int` 上限的压缩 metadata 始终被拒绝,压缩 metadata 必须严格小于原始大小,空 data block 也是非法的。 +- 所有归档读取命令都对存储和未压缩 metadata 施加每归档预算(`--max-metadata-size`,默认 1 GiB,`0` 表示不限制),并在分配任一缓冲区之前检查。超过 LZ4 `int` 上限的压缩 metadata 始终被拒绝,压缩 metadata 必须严格小于原始大小。 ### 版本编码与兼容性 diff --git a/src/core/block_store.cpp b/src/core/block_store.cpp index ad9befc..fbe0d18 100644 --- a/src/core/block_store.cpp +++ b/src/core/block_store.cpp @@ -1300,6 +1300,10 @@ namespace ctar { return s; } + if (auto graph_status = pack_file_handle_.ValidateDirectoryGraph(); !graph_status) + { + return error_corruption("corrupt archive '{}': {}", pack_file_path, graph_status.error().message()); + } if (static_cast(meta_end - meta_ptr) < sizeof(uint64_t)) { return error_corruption("corrupt archive '{}': missing data block count", pack_file_path); diff --git a/src/core/file_format.cpp b/src/core/file_format.cpp index b855124..26213c5 100644 --- a/src/core/file_format.cpp +++ b/src/core/file_format.cpp @@ -8,6 +8,8 @@ #include #include #include +#include +#include #include "file_format.h" #include "src/utils/coding.h" @@ -482,6 +484,92 @@ namespace return {}; } + Status ValidateDirectoryGraph(const PackFileMeta& meta) + { + // Directory entries are identified by their presence in dir_entry_records; + // entry_type is not reliable for directories in existing archives (the + // scanner re-adds each directory with a default EntryMeta), so the graph + // structure is validated by id membership only. + if (meta.dir_entry_records.find(kRootDirId) == meta.dir_entry_records.end()) + { + return error_corruption("directory graph: root directory {} has no entry", kRootDirId); + } + + // Every non-root directory must have exactly one parent; duplicate edges and + // multiple parents are rejected here, before any traversal can loop. + std::unordered_map parent_of; + parent_of.reserve(meta.dir_entry_records.size()); + for (const auto& children_entry : meta.dir_id_to_child_dir_ids) + { + const entry_id_t parent_id = children_entry.first; + if (meta.dir_entry_records.find(parent_id) == meta.dir_entry_records.end()) + { + return error_corruption("directory graph: parent {} has no directory entry", parent_id); + } + for (const entry_id_t child_id : children_entry.second) + { + if (child_id == parent_id) + { + return error_corruption("directory graph: directory {} lists itself as a child", parent_id); + } + if (child_id == kRootDirId) + { + return error_corruption("directory graph: root directory {} appears as a child", kRootDirId); + } + if (meta.dir_entry_records.find(child_id) == meta.dir_entry_records.end()) + { + return error_corruption("directory graph: child {} of directory {} has no entry", child_id, + parent_id); + } + if (!parent_of.emplace(child_id, parent_id).second) + { + return error_corruption("directory graph: directory {} has more than one parent", child_id); + } + } + } + for (const auto& dir_entry : meta.dir_entry_records) + { + if (dir_entry.first != kRootDirId && parent_of.find(dir_entry.first) == parent_of.end()) + { + return error_corruption("directory graph: directory {} has no parent", dir_entry.first); + } + } + + // Breadth-first traversal from the root detects cycles reachable from it and + // directories that are only part of a disconnected cycle. The depth limit is + // a renderer concern, not an archive invariant: unpack and stat must accept + // deeper valid trees, while the recursive renderer rejects them. + std::unordered_set visited; + visited.reserve(meta.dir_entry_records.size()); + std::vector queue; + queue.reserve(meta.dir_entry_records.size()); + queue.push_back(kRootDirId); + visited.insert(kRootDirId); + for (size_t head = 0; head < queue.size(); ++head) + { + const entry_id_t dir_id = queue[head]; + const auto children = meta.dir_id_to_child_dir_ids.find(dir_id); + if (children == meta.dir_id_to_child_dir_ids.end()) + { + continue; + } + for (const entry_id_t child_id : children->second) + { + if (!visited.insert(child_id).second) + { + return error_corruption("directory graph: cycle detected at directory {}", child_id); + } + queue.push_back(child_id); + } + } + if (visited.size() != meta.dir_entry_records.size()) + { + return error_corruption("directory graph: {} directories are unreachable from root", + meta.dir_entry_records.size() - visited.size()); + } + return {}; + } + PackFileMeta::PackFileMeta() { dir_name_data.reserve(kEntryNameBufferSize); @@ -1168,9 +1256,37 @@ namespace } + Status PackFileHandle::ValidateDirectoryGraph() const + { + return ctar::ValidateDirectoryGraph(pack_file_meta_); + } + Status PackFileHandle::RenderDirListing(std::ostream& out, entry_id_t dir_id, const std::string& prefix, const OutputMode output_mode, bool human_readable, bool has_header) const { + std::unordered_set active; + return RenderDirListingImpl(out, dir_id, prefix, output_mode, human_readable, has_header, active, 0); + } + + Status PackFileHandle::RenderDirListingImpl(std::ostream& out, entry_id_t dir_id, const std::string& prefix, + const OutputMode output_mode, bool human_readable, bool has_header, + std::unordered_set& active, const size_t depth) const + { + if (depth > kMaxDirectoryDepth) + { + return error_corruption("directory tree depth exceeds the limit {}", kMaxDirectoryDepth); + } + if (!active.insert(dir_id).second) + { + return error_corruption("directory cycle detected at directory {}", dir_id); + } + struct ActiveDirectoryGuard + { + std::unordered_set& active; + entry_id_t dir_id; + ~ActiveDirectoryGuard() { active.erase(dir_id); } + } active_guard{active, dir_id}; + auto dir_name_res = GetDirPathByDirId(dir_id); if (!dir_name_res) { @@ -1234,8 +1350,8 @@ namespace if (entry.is_directory) { std::string new_prefix = prefix + (is_last ? " " : "│ "); - auto status = - RenderDirListing(out, entry.id, new_prefix, OutputMode::TREE, human_readable, has_header); + auto status = RenderDirListingImpl(out, entry.id, new_prefix, OutputMode::TREE, human_readable, + has_header, active, depth + 1); if (!status) return status; } @@ -1277,7 +1393,8 @@ namespace } else { - auto status = RenderDirListing(out, entry.id, prefix, output_mode, human_readable, has_header); + auto status = RenderDirListingImpl(out, entry.id, prefix, output_mode, human_readable, has_header, + active, depth + 1); if (!status) return status; } diff --git a/src/core/file_format.h b/src/core/file_format.h index fdf776b..6e45bd2 100644 --- a/src/core/file_format.h +++ b/src/core/file_format.h @@ -12,6 +12,7 @@ #include #include #include +#include #include "options.h" #include "sorted_map.h" @@ -279,6 +280,11 @@ namespace ctar [[nodiscard]] const std::string& GetUserName(uint32_t uid); [[nodiscard]] const std::string& GetGroupName(uint32_t gid); + /// @brief Recursive renderer with cycle/depth guards; see RenderDirListing. + Status RenderDirListingImpl(std::ostream& out, entry_id_t dir_id, const std::string& prefix, + OutputMode output_mode, bool human_readable, bool has_header, + std::unordered_set& active, size_t depth) const; + public: /// @brief Scan host filesystem directory, import entries into pack metadata /// @param root_path designated host‑system root directory for scanning @@ -351,6 +357,10 @@ namespace ctar /// @brief Number of directory entries, including the root directory. [[nodiscard]] size_t GetDirectoryCount() const { return pack_file_meta_.dir_entry_records.size(); } + /// @brief Validate the deserialized directory graph before rendering or unpacking. + /// @return Status::Ok when the graph is a tree rooted at kRootDirId; kCorruption otherwise + [[nodiscard]] Status ValidateDirectoryGraph() const; + /// @brief Add entry metadata into map, append name string to data buffer /// @param key unique entry id /// @param name entry dir/file name @@ -545,5 +555,15 @@ namespace ctar /// @return Ok on success, kCorruption otherwise Status ValidateDataBlockMeta(const DataBlockMeta& block_meta, const EntryPathResolver& path_of = {}, uint64_t max_original_size = kDefaultMaxDecompressedFileSize); + + /// @brief Validate the directory graph in a deserialized PackFileMeta. + /// + /// The child maps are untrusted: they must describe a tree rooted at kRootDirId, + /// with exactly one parent for every non-root directory, no cycles or duplicate + /// edges, and every directory reachable from the root. Chains deeper than + /// kMaxDirectoryDepth are rejected so the recursive renderer cannot overflow. + /// @param meta deserialized metadata index + /// @return Ok on success, kCorruption otherwise + Status ValidateDirectoryGraph(const PackFileMeta& meta); }; // namespace ctar #endif // CTAR_FORMAT_H diff --git a/src/core/options.h b/src/core/options.h index 3233ac9..fb2dbf2 100644 --- a/src/core/options.h +++ b/src/core/options.h @@ -51,6 +51,12 @@ namespace ctar // --max-metadata-size (0 disables the limit). constexpr uint64_t kDefaultMaxMetadataSize = 1ULL * unit::GiB; + // Maximum depth accepted by the recursive renderer (tree/ls/dump). This is a + // rendering limit, not an archive invariant: unpack and stat accept deeper valid + // trees, while the renderer returns kCorruption instead of overflowing its stack. + // 128 still leaves headroom under ASan stack frames. + constexpr size_t kMaxDirectoryDepth = 128; + // Thread-local read/block buffers larger than this are trimmed back to this // size after a task, instead of being held until the process exits. constexpr size_t kMaxRetainedBufferBytes = 128UL * unit::MiB; diff --git a/test/cases/test_block_store.cpp b/test/cases/test_block_store.cpp index 8fdcef2..ef5e20e 100644 --- a/test/cases/test_block_store.cpp +++ b/test/cases/test_block_store.cpp @@ -2,6 +2,7 @@ #include #include #include +#include #include #include #include @@ -927,6 +928,112 @@ namespace ctar } + TEST(MalformedArchive, RejectsCyclicDirectoryGraph) + { + MalformedArchiveFixture fixture; + fixture.Create(); + std::string bytes = fixture.Bytes(); + + constexpr size_t kMetadataOffsetField = 96; + constexpr size_t kMetadataSizeField = 112; + constexpr size_t kMetadataTypeField = 120; + constexpr size_t kMetadataChecksumField = 128; + constexpr size_t kEntryRecordSize = 2 * sizeof(uint64_t) + 176; + + const size_t metadata_offset = ReadU64At(bytes, kMetadataOffsetField); + const size_t metadata_size = ReadU64At(bytes, kMetadataSizeField); + ASSERT_GT(metadata_size, 0U); + ASSERT_EQ(ReadU64At(bytes, kMetadataTypeField), static_cast(CompressionType::kNone)); + + size_t pos = metadata_offset; + const size_t metadata_end = metadata_offset + metadata_size; + const auto read_u64 = [&]() + { + EXPECT_LE(pos + sizeof(uint64_t), metadata_end); + const uint64_t value = ReadU64At(bytes, pos); + pos += sizeof(uint64_t); + return value; + }; + + // PackFileMeta: four scalars, two name buffers, then the two entry maps. + for (int i = 0; i < 4; ++i) + { + (void)read_u64(); + } + pos += static_cast(read_u64()); // dir_name_data + pos += static_cast(read_u64()); // file_name_data + for (int map = 0; map < 2; ++map) + { + const uint64_t count = read_u64(); + pos += static_cast(count) * (sizeof(uint64_t) + kEntryRecordSize); + } + + // Patch the root's first child into a self-cycle, then make the checksum valid + // so the archive reaches the directory-graph validation. + const uint64_t map_count = read_u64(); + bool patched = false; + for (uint64_t entry = 0; entry < map_count; ++entry) + { + const entry_id_t parent = read_u64(); + const uint64_t child_count = read_u64(); + if (parent == kRootDirId && child_count > 0) + { + WriteU64At(bytes, pos, kRootDirId); + patched = true; + break; + } + pos += static_cast(child_count) * sizeof(uint64_t); + } + ASSERT_TRUE(patched); + + const std::string metadata = bytes.substr(metadata_offset, metadata_size); + WriteU64At(bytes, kMetadataChecksumField, XXH64(metadata.data(), metadata.size(), kHashSeed)); + + const Status status = fixture.Unpack(bytes); + ASSERT_FALSE(status); + EXPECT_EQ(status.error().type(), ErrorType::kCorruption); + EXPECT_NE(status.error().err_message.find("directory graph"), std::string::npos) + << status.error().message(); + fixture.Cleanup(); + } + + TEST(DirectoryGraph, DeepTreeUnpacksButDoesNotRender) + { + const fs::path root{"deep_directory_graph_test"}; + const fs::path source = root / "source"; + const fs::path archive = root / "deep.ctar"; + const fs::path out = root / "out"; + fs::remove_all(root); + fs::create_directories(source); + fs::path deep = source; + for (size_t i = 0; i < kMaxDirectoryDepth + 2; ++i) + { + deep /= "d"; + fs::create_directory(deep); + } + std::ofstream(deep / "f.txt") << "x"; + + BlockStore packer; + ASSERT_TRUE(packer.Scan(source.string())); + ASSERT_TRUE(packer.PackPipeline(archive.string())); + + // Depth is not an archive invariant: unpack must restore the valid tree. + BlockStore unpacker; + ASSERT_TRUE(unpacker.UnPackPipeline(archive.string(), out.string(), true)); + EXPECT_TRUE(fs::exists(out / source / fs::relative(deep, source) / "f.txt")); + + // The recursive renderer rejects the deep tree instead of overflowing. + BlockStore reader; + ASSERT_TRUE(reader.RestoreBlocksFromPack(archive.string())); + std::ostringstream rendered; + const Status status = reader.RenderDirectoryTree(rendered); + ASSERT_FALSE(status); + EXPECT_EQ(status.error().type(), ErrorType::kCorruption); + EXPECT_NE(status.error().err_message.find("depth"), std::string::npos); + + fs::remove_all(root); + } + namespace { struct UnpackPolicyFixture diff --git a/test/cases/test_file_format.cpp b/test/cases/test_file_format.cpp index 0b3fe23..f1622ad 100644 --- a/test/cases/test_file_format.cpp +++ b/test/cases/test_file_format.cpp @@ -1,4 +1,5 @@ #include +#include #include #include #include @@ -925,6 +926,210 @@ namespace ctar } + namespace + { + void AddDirEntry(PackFileMeta& meta, const entry_id_t id) + { + meta.dir_entry_records.put(id, EntryRecord{}); + } + } // namespace + + TEST(DirectoryGraph, AcceptsRootOnly) + { + PackFileMeta meta; + AddDirEntry(meta, kRootDirId); + EXPECT_TRUE(ValidateDirectoryGraph(meta)); + } + + TEST(DirectoryGraph, AcceptsValidTree) + { + PackFileMeta meta; + AddDirEntry(meta, 1); + AddDirEntry(meta, 2); + AddDirEntry(meta, 3); + meta.dir_id_to_child_dir_ids.put(1, {2}); + meta.dir_id_to_child_dir_ids.put(2, {3}); + EXPECT_TRUE(ValidateDirectoryGraph(meta)); + } + + TEST(DirectoryGraph, RejectsMissingRoot) + { + PackFileMeta meta; + AddDirEntry(meta, 2); + const Status status = ValidateDirectoryGraph(meta); + ASSERT_FALSE(status); + EXPECT_EQ(status.error().type(), ErrorType::kCorruption); + EXPECT_NE(status.error().err_message.find("root"), std::string::npos); + } + + TEST(DirectoryGraph, RejectsSelfCycle) + { + PackFileMeta meta; + AddDirEntry(meta, 1); + meta.dir_id_to_child_dir_ids.put(1, {1}); + const Status status = ValidateDirectoryGraph(meta); + ASSERT_FALSE(status); + EXPECT_NE(status.error().err_message.find("lists itself"), std::string::npos); + } + + TEST(DirectoryGraph, RejectsRootAsChild) + { + PackFileMeta meta; + AddDirEntry(meta, 1); + AddDirEntry(meta, 2); + meta.dir_id_to_child_dir_ids.put(1, {2}); + meta.dir_id_to_child_dir_ids.put(2, {1}); + const Status status = ValidateDirectoryGraph(meta); + ASSERT_FALSE(status); + EXPECT_NE(status.error().err_message.find("root directory"), std::string::npos); + } + + TEST(DirectoryGraph, RejectsMultipleParents) + { + PackFileMeta meta; + AddDirEntry(meta, 1); + AddDirEntry(meta, 2); + AddDirEntry(meta, 3); + meta.dir_id_to_child_dir_ids.put(1, {2}); + meta.dir_id_to_child_dir_ids.put(3, {2}); + const Status status = ValidateDirectoryGraph(meta); + ASSERT_FALSE(status); + EXPECT_NE(status.error().err_message.find("more than one parent"), std::string::npos); + } + + TEST(DirectoryGraph, RejectsDisconnectedCycle) + { + PackFileMeta meta; + AddDirEntry(meta, 1); + AddDirEntry(meta, 2); + AddDirEntry(meta, 3); + AddDirEntry(meta, 4); + meta.dir_id_to_child_dir_ids.put(1, {3}); + meta.dir_id_to_child_dir_ids.put(2, {4}); + meta.dir_id_to_child_dir_ids.put(4, {2}); + const Status status = ValidateDirectoryGraph(meta); + ASSERT_FALSE(status); + EXPECT_NE(status.error().err_message.find("unreachable"), std::string::npos); + } + + TEST(DirectoryGraph, RejectsUnknownChild) + { + PackFileMeta meta; + AddDirEntry(meta, 1); + meta.dir_id_to_child_dir_ids.put(1, {2}); + const Status status = ValidateDirectoryGraph(meta); + ASSERT_FALSE(status); + EXPECT_NE(status.error().err_message.find("child 2"), std::string::npos); + } + + TEST(DirectoryGraph, RejectsUnknownParent) + { + PackFileMeta meta; + AddDirEntry(meta, 1); + AddDirEntry(meta, 2); + meta.dir_id_to_child_dir_ids.put(3, {2}); + const Status status = ValidateDirectoryGraph(meta); + ASSERT_FALSE(status); + EXPECT_NE(status.error().err_message.find("parent 3"), std::string::npos); + } + + TEST(DirectoryGraph, RejectsMissingParent) + { + PackFileMeta meta; + AddDirEntry(meta, 1); + AddDirEntry(meta, 2); + const Status status = ValidateDirectoryGraph(meta); + ASSERT_FALSE(status); + EXPECT_NE(status.error().err_message.find("directory 2 has no parent"), std::string::npos); + } + + TEST(DirectoryGraph, RejectsDuplicateChild) + { + PackFileMeta meta; + AddDirEntry(meta, 1); + AddDirEntry(meta, 2); + meta.dir_id_to_child_dir_ids.put(1, {2, 2}); + const Status status = ValidateDirectoryGraph(meta); + ASSERT_FALSE(status); + EXPECT_NE(status.error().err_message.find("more than one parent"), std::string::npos); + } + + TEST(DirectoryGraph, AcceptsDeepChain) + { + PackFileMeta meta; + const size_t dir_count = kMaxDirectoryDepth + 2; + for (size_t id = 1; id <= dir_count; ++id) + { + AddDirEntry(meta, static_cast(id)); + } + for (size_t id = 1; id < dir_count; ++id) + { + meta.dir_id_to_child_dir_ids.put(static_cast(id), {static_cast(id + 1)}); + } + EXPECT_TRUE(ValidateDirectoryGraph(meta)); + } + + TEST(DirectoryGraph, RendererRejectsDepth) + { + PackFileMeta meta; + meta.dir_name_data = "d"; + const size_t dir_count = kMaxDirectoryDepth + 2; + for (size_t id = 1; id <= dir_count; ++id) + { + EntryRecord record{}; + record.name_handle.offset = 0; + record.name_handle.len = 1; + record.entry_meta.entry_type = EntryType::DIRECTORY; + meta.dir_entry_records.put(static_cast(id), record); + } + for (size_t id = 1; id < dir_count; ++id) + { + meta.dir_id_to_child_dir_ids.put(static_cast(id), {static_cast(id + 1)}); + } + + std::string bytes; + meta.Serialize(&bytes); + PackFileHandle handle; + const char* ptr = bytes.data(); + ASSERT_TRUE(handle.DeserializePackFileMeta(ptr, bytes.data() + bytes.size())); + + std::ostringstream out; + const Status status = handle.RenderDirListing(out); + ASSERT_FALSE(status); + EXPECT_EQ(status.error().type(), ErrorType::kCorruption); + EXPECT_NE(status.error().err_message.find("depth"), std::string::npos); + } + + TEST(DirectoryGraph, RendererRejectsCycle) + { + PackFileMeta meta; + meta.dir_name_data = "rootchild"; + EntryRecord root{}; + root.name_handle.offset = 0; + root.name_handle.len = 4; + root.entry_meta.entry_type = EntryType::DIRECTORY; + EntryRecord child{}; + child.name_handle.offset = 4; + child.name_handle.len = 5; + child.entry_meta.entry_type = EntryType::DIRECTORY; + meta.dir_entry_records.put(1, root); + meta.dir_entry_records.put(2, child); + meta.dir_id_to_child_dir_ids.put(1, {2}); + meta.dir_id_to_child_dir_ids.put(2, {1}); + + std::string bytes; + meta.Serialize(&bytes); + PackFileHandle handle; + const char* ptr = bytes.data(); + ASSERT_TRUE(handle.DeserializePackFileMeta(ptr, bytes.data() + bytes.size())); + + std::ostringstream out; + const Status status = handle.RenderDirListing(out); + ASSERT_FALSE(status); + EXPECT_EQ(status.error().type(), ErrorType::kCorruption); + EXPECT_NE(status.error().err_message.find("cycle"), std::string::npos); + } + } // namespace ctar int main(int argc, char** argv)