diff --git a/bridge/mitmproxy/capture.py b/bridge/mitmproxy/capture.py index fc34451b21..16cec1819c 100644 --- a/bridge/mitmproxy/capture.py +++ b/bridge/mitmproxy/capture.py @@ -40,7 +40,7 @@ class BoundedReader: def read(self, count): if count < 0 or count > self.size - self.handle.tell(): - raise CaptureFailure("format", "Native record declares bytes beyond the retained capture.") + raise CaptureFailure("malformed", "Native record declares bytes beyond the retained capture.") return self.handle.read(count) @@ -295,7 +295,7 @@ def project_record(state, secrets, max_depth): result = [] for index, field in enumerate(value): if not isinstance(field, (list, tuple)) or len(field) != 2 or not isinstance(field[0], bytes): - raise CaptureFailure("format", "Native header/trailer is not an ordered byte pair.", pointer(path, index)) + raise CaptureFailure("malformed", "Native header/trailer is not an ordered byte pair.", pointer(path, index)) result.append([visit(field[0], pointer(pointer(path, index), 0), depth + 2), visit(field[1], pointer(pointer(path, index), 1), depth + 2, field[0].lower() in CREDENTIALS, field[0].lower() in {b"location", b"referer", b"origin"}, base_scheme if field[0].lower() == b"location" else None)]) return result return [visit(item, pointer(path, index), depth + 1, base_scheme=base_scheme) for index, item in enumerate(value)] @@ -309,7 +309,7 @@ def project_record(state, secrets, max_depth): result = {} for key, item in value.items(): if not isinstance(key, str): - raise CaptureFailure("format", "Native record has a non-string dictionary key.", path) + raise CaptureFailure("malformed", "Native record has a non-string dictionary key.", path) if any(secret in key for secret in secrets): # Validate the omitted subtree too, then discard all of its # coordinates rather than inventing a replacement identity. @@ -340,9 +340,9 @@ def decode(request): except RecursionError: raise CaptureFailure("unsupported", "Native parser reached Python's recursion limit at byte offset " + str(start) + ". max_nesting_depth does not raise that upstream limit.") from None except (ValueError, IndexError, UnicodeError, EOFError): - raise CaptureFailure("format", "Malformed native record at byte offset " + str(start) + ".") from None + raise CaptureFailure("malformed", "Malformed native record at byte offset " + str(start) + ".") from None if not isinstance(state, dict): - raise CaptureFailure("format", "Native flow record must be a dictionary at byte offset " + str(start) + ".") + raise CaptureFailure("malformed", "Native flow record must be a dictionary at byte offset " + str(start) + ".") records.append({"ordinal": len(records), "location": {"kind": "byte-range", "offset": start, "bytes": handle.tell() - start}, **project_record(state, request["sensitive_values"], request["budgets"]["depth"]), "limitations": ["Fields are original native states without FlowReader migration. Binary fields contain exact producer bytes; reported UTF-8 strings for those fields are derived display views. Unknown flow/version extensions are retained without interpretation."]}) return {"decoder": {"id": "mitmproxy-native-tnetstring", "name": "REA offline native mitmproxy adapter", "version": PROFILE}, "container": {"reported": None, "numeric_literals": [], "redactions": [], "records_pointer": None}, "total_records": len(records), "records": records} diff --git a/bridge/pwntools/layout_impl.py b/bridge/pwntools/layout_impl.py index f3ab879cad..ebf64c12e2 100644 --- a/bridge/pwntools/layout_impl.py +++ b/bridge/pwntools/layout_impl.py @@ -38,13 +38,13 @@ def file_range(offset, size, length): def location(offset, size, length): if not file_range(offset, size, length): - raise LayoutFailure("format", "ELF contains a file-backed range outside the selected snapshot.") + raise LayoutFailure("malformed", "ELF contains a file-backed range outside the selected snapshot.") return {"offset": address(offset), "bytes": address(size)} def _name_in_validated_table(display, table_start, table_size, offset, content, length, cache=None): if not 0 <= offset < table_size: - raise LayoutFailure("format", f"ELF name offset {offset} lies outside its declared string table of {table_size} bytes at file offset {table_start}.") + raise LayoutFailure("malformed", f"ELF name offset {offset} lies outside its declared string table of {table_size} bytes at file offset {table_start}.") if cache is not None: cached = cache.get(offset) if cached is not None: @@ -64,11 +64,11 @@ def _name_in_validated_table(display, table_start, table_size, offset, content, limit = table_start + table_size end = content.find(b"\0", start, limit) if end < 0: - raise LayoutFailure("format", "ELF name lacks a terminator within its reported string table.") + raise LayoutFailure("malformed", "ELF name lacks a terminator within its reported string table.") raw = content[start:end] raw_size = len(raw) + 1 if not file_range(start, raw_size, length): - raise LayoutFailure("format", "ELF contains a file-backed range outside the selected snapshot.") + raise LayoutFailure("malformed", "ELF contains a file-backed range outside the selected snapshot.") b64 = base64.b64encode(raw).decode("ascii") off_hex = address(start) bytes_hex = address(raw_size) @@ -90,7 +90,7 @@ def inspect_elf(path, cache): content = path.read_bytes() length = len(content) if length < 4 or content[:4] != b"\x7fELF": - raise LayoutFailure("format", "Selected object does not contain an ELF header.") + raise LayoutFailure("malformed", "Selected object does not contain an ELF header.") if length < 16: raise LayoutFailure("truncated", "Selected ELF identification is truncated.") if content[4] not in (1, 2) or content[5] not in (1, 2): @@ -118,9 +118,9 @@ def inspect_elf(path, cache): compressed_strtabs = [] if section_count: if headers.header.e_shentsize < headers.structs.Elf_Shdr.sizeof(): - raise LayoutFailure("format", "ELF section-header entry is shorter than the required structure.") + raise LayoutFailure("malformed", "ELF section-header entry is shorter than the required structure.") if not file_range(headers.header.e_shoff, section_count * headers.header.e_shentsize, length): - raise LayoutFailure("format", "ELF contains a file-backed range outside the selected snapshot.") + raise LayoutFailure("malformed", "ELF contains a file-backed range outside the selected snapshot.") # Upstream symbol, relocation and dynamic access reads stored stream # bytes, while this profile reports logical names and file coordinates. # A string table is read only when it names sections or symbols. @@ -141,29 +141,29 @@ def inspect_elf(path, cache): consumed_strings.add(raw_header.sh_link) segment_count = headers.num_segments() if segment_count and not file_range(headers.header.e_phoff, segment_count * headers.header.e_phentsize, length): - raise LayoutFailure("format", "ELF contains a file-backed range outside the selected snapshot.") + raise LayoutFailure("malformed", "ELF contains a file-backed range outside the selected snapshot.") if headers.header.e_shstrndx == 0xffff and section_count == 0: - raise LayoutFailure("format", "ELF extended section-name index requires a declared section-zero header.") + raise LayoutFailure("malformed", "ELF extended section-name index requires a declared section-zero header.") raw_name_index = headers.header.e_shstrndx if 0xff00 <= raw_name_index < 0xffff: - raise LayoutFailure("format", f"ELF section-name index {raw_name_index} is reserved and cannot directly reference a section.") + raise LayoutFailure("malformed", f"ELF section-name index {raw_name_index} is reserved and cannot directly reference a section.") section_name_index = headers.get_shstrndx() if raw_name_index == 0xffff and section_name_index < 0xff00: - raise LayoutFailure("format", f"ELF SHN_XINDEX resolves to ordinary index {section_name_index}; the escape requires an index at least SHN_LORESERVE (0xff00).") + raise LayoutFailure("malformed", f"ELF SHN_XINDEX resolves to ordinary index {section_name_index}; the escape requires an index at least SHN_LORESERVE (0xff00).") if section_name_index != 0: if section_name_index >= section_count: - raise LayoutFailure("format", f"ELF section-name table index {section_name_index} lies outside the declared section count {section_count}.") + raise LayoutFailure("malformed", f"ELF section-name table index {section_name_index} lies outside the declared section count {section_count}.") names_header = headers._get_section_header(section_name_index) if names_header.sh_type != "SHT_STRTAB": - raise LayoutFailure("format", f"ELF section-name table {section_name_index} is not SHT_STRTAB.") + raise LayoutFailure("malformed", f"ELF section-name table {section_name_index} is not SHT_STRTAB.") consumed_strings.add(section_name_index) for index in compressed_strtabs: if index in consumed_strings: raise LayoutFailure("unsupported-target", f"ELF section {index} (SHT_STRTAB) is SHF_COMPRESSED; logical metadata and its source coordinates are not decoded by this profile.") if section_name_index != 0 and not file_range(names_header.sh_offset, names_header.sh_size, length): - raise LayoutFailure("format", "ELF contains a file-backed range outside the selected snapshot.") + raise LayoutFailure("malformed", "ELF contains a file-backed range outside the selected snapshot.") except (ELFError, ValueError, OverflowError, AssertionError, IndexError) as error: - raise LayoutFailure("format", str(error)) from error + raise LayoutFailure("malformed", str(error)) from error class LayoutELF(ELF): def search(self, needle, writable=False, executable=False): # This adapter exposes structural facts, GOT/PLT and mitigation @@ -237,7 +237,7 @@ def inspect_elf(path, cache): shstr_header = getattr(shstrings, "header", None) if shstrings is not None else None shstr_valid = shstr_header is not None and shstr_header.sh_type == "SHT_STRTAB" if shstr_valid and not file_range(shstr_header.sh_offset, shstr_header.sh_size, length): - raise LayoutFailure("format", "ELF contains a file-backed range outside the selected snapshot.") + raise LayoutFailure("malformed", "ELF contains a file-backed range outside the selected snapshot.") shstr_start = shstr_header.sh_offset if shstr_valid else 0 shstr_size = shstr_header.sh_size if shstr_valid else 0 shstr_cache = {} if shstr_valid else None @@ -256,10 +256,10 @@ def inspect_elf(path, cache): sh_type = h.sh_type backing = sh_type not in ("SHT_NOBITS", "SHT_NULL") if backing and not file_range(h.sh_offset, h.sh_size, length): - raise LayoutFailure("format", "ELF contains a file-backed range outside the selected snapshot.") + raise LayoutFailure("malformed", "ELF contains a file-backed range outside the selected snapshot.") hdr_off = e_shoff + index * e_shentsize if not file_range(hdr_off, e_shentsize, length): - raise LayoutFailure("format", "ELF contains a file-backed range outside the selected snapshot.") + raise LayoutFailure("malformed", "ELF contains a file-backed range outside the selected snapshot.") if shstrings is None: sec_name = {"display": "", "bytes_base64": None, "location": None, "unknown_reason": "ELF declares no section-name table (SHN_UNDEF index 0)."} @@ -280,10 +280,10 @@ def inspect_elf(path, cache): if sh_type in ("SHT_SYMTAB", "SHT_DYNSYM"): entsize = h.sh_entsize if entsize < sym_sizeof: - raise LayoutFailure("format", f"ELF symbol entry is smaller than the decoded Elf{bits}_Sym structure.") + raise LayoutFailure("malformed", f"ELF symbol entry is smaller than the decoded Elf{bits}_Sym structure.") sh_link = h.sh_link if sh_link >= num_sections or all_sections[sh_link].header.sh_type != "SHT_STRTAB": - raise LayoutFailure("format", f"ELF symbol table {index} links to invalid string table {sh_link}.") + raise LayoutFailure("malformed", f"ELF symbol table {index} links to invalid string table {sh_link}.") strings_hdr = all_sections[sh_link].header str_start = strings_hdr.sh_offset str_size = strings_hdr.sh_size @@ -297,13 +297,13 @@ def inspect_elf(path, cache): for entry, symbol in enumerate(section.iter_symbols()): if not strtab_checked: if not file_range(str_start, str_size, length): - raise LayoutFailure("format", "ELF contains a file-backed range outside the selected snapshot.") + raise LayoutFailure("malformed", "ELF contains a file-backed range outside the selected snapshot.") validated_strtabs.add(sh_link) strtab_checked = True raw = symbol.entry entry_off = sym_base_off + entry * entsize if not file_range(entry_off, entsize, length): - raise LayoutFailure("format", "ELF contains a file-backed range outside the selected snapshot.") + raise LayoutFailure("malformed", "ELF contains a file-backed range outside the selected snapshot.") raw_info = raw.st_info sym_type = raw_info.type shndx = raw.st_shndx @@ -337,17 +337,17 @@ def inspect_elf(path, cache): entsize = h.sh_entsize if h.sh_size % entsize != 0: raise LayoutFailure( - "format", + "malformed", f"ELF relocation section {index} size is not a multiple of its {entsize}-byte entries.", ) sh_info = h.sh_info if is_et_rel and sh_info >= num_sections: - raise LayoutFailure("format", f"ELF relocation section {index} references missing target section {sh_info}.") + raise LayoutFailure("malformed", f"ELF relocation section {index} references missing target section {sh_info}.") sh_link = h.sh_link symbol_table = None if sh_link != 0: if sh_link >= num_sections or all_sections[sh_link].header.sh_type not in ("SHT_SYMTAB", "SHT_DYNSYM"): - raise LayoutFailure("format", f"ELF relocation section {index} links to invalid symbol table {sh_link}.") + raise LayoutFailure("malformed", f"ELF relocation section {index} links to invalid symbol table {sh_link}.") symbol_table = all_sections[sh_link] num_symbols = 0 if symbol_table is None else symbol_table.num_symbols() entsize_hex = address(entsize) @@ -359,10 +359,10 @@ def inspect_elf(path, cache): raw = relocation.entry sym_idx = raw.r_info_sym if sym_idx != 0 and (symbol_table is None or sym_idx >= num_symbols): - raise LayoutFailure("format", f"ELF relocation section {index} entry {entry} references missing symbol {sym_idx} in table {sh_link}.") + raise LayoutFailure("malformed", f"ELF relocation section {index} entry {entry} references missing symbol {sym_idx} in table {sh_link}.") entry_off = rel_base_off + entry * entsize if not file_range(entry_off, entsize, length): - raise LayoutFailure("format", "ELF contains a file-backed range outside the selected snapshot.") + raise LayoutFailure("malformed", "ELF contains a file-backed range outside the selected snapshot.") offset_hex = address(raw.r_offset) if not is_et_rel: target = {"kind": "linked-virtual-address", "address": offset_hex} @@ -400,12 +400,12 @@ def inspect_elf(path, cache): p_type = h.p_type backing = p_type != "PT_NULL" and h.p_filesz != 0 if backing and not file_range(h.p_offset, h.p_filesz, length): - raise LayoutFailure("format", "ELF contains a file-backed range outside the selected snapshot.") + raise LayoutFailure("malformed", "ELF contains a file-backed range outside the selected snapshot.") if p_type == "PT_LOAD" and h.p_memsz < h.p_filesz: - raise LayoutFailure("format", "ELF load segment memory size is smaller than its file size.") + raise LayoutFailure("malformed", "ELF load segment memory size is smaller than its file size.") phdr_off = e_phoff + index * e_phentsize if not file_range(phdr_off, e_phentsize, length): - raise LayoutFailure("format", "ELF contains a file-backed range outside the selected snapshot.") + raise LayoutFailure("malformed", "ELF contains a file-backed range outside the selected snapshot.") segments.append({ "index": index, "type": p_type, "offset": address(h.p_offset), "header_location": {"offset": address(phdr_off), "bytes": e_phentsize_hex}, @@ -431,10 +431,10 @@ def inspect_elf(path, cache): elif d_tag == "DT_NEEDED": dt_needed.append(tag.d_val) else: - raise LayoutFailure("format", f"ELF dynamic segment {index} has no complete DT_NULL terminator within its reported file range.") + raise LayoutFailure("malformed", f"ELF dynamic segment {index} has no complete DT_NULL terminator within its reported file range.") if dt_needed: if not dt_strtab or not dt_strsz: - raise LayoutFailure("format", "ELF dependency requires DT_STRTAB and DT_STRSZ.") + raise LayoutFailure("malformed", "ELF dependency requires DT_STRTAB and DT_STRSZ.") if len(dt_strtab) != 1 or len(dt_strsz) != 1: raise LayoutFailure("unsupported-target", "ELF dependency string-table tags are ambiguous: " + repr({"DT_STRTAB": dt_strtab, "DT_STRSZ": dt_strsz})) dyn_start, dyn_size = dt_strtab[0], dt_strsz[0] @@ -442,7 +442,7 @@ def inspect_elf(path, cache): dyn_cache = {} for needed_offset in dt_needed: if not 0 <= needed_offset < dyn_size: - raise LayoutFailure("format", f"ELF dependency name offset {needed_offset} lies outside declared DT_STRSZ {dyn_size}.") + raise LayoutFailure("malformed", f"ELF dependency name offset {needed_offset} lies outside declared DT_STRSZ {dyn_size}.") if dynstr_offset is None: offsets = { lh.p_offset + dyn_start - lh.p_vaddr @@ -453,13 +453,13 @@ def inspect_elf(path, cache): raise LayoutFailure("unsupported-target", "Dynamic string table lacks a unique file-backed mapping: " + repr({"DT_STRTAB": dt_strtab, "DT_STRSZ": dt_strsz, "candidate_file_offsets": sorted(offsets)})) dynstr_offset = offsets.pop() if not file_range(dynstr_offset, dyn_size, length): - raise LayoutFailure("format", "ELF contains a file-backed range outside the selected snapshot.") + raise LayoutFailure("malformed", "ELF contains a file-backed range outside the selected snapshot.") needed.append(_name_in_validated_table(None, dynstr_offset, dyn_size, needed_offset, content, length, dyn_cache)) elif p_type == "PT_INTERP": raw = content[h.p_offset:h.p_offset + h.p_filesz] end = raw.find(b"\0") if end < 0: - raise LayoutFailure("format", "ELF interpreter lacks a reported terminator.") + raise LayoutFailure("malformed", "ELF interpreter lacks a reported terminator.") interp_raw = raw[:end] interpreters.append({"display": interp_raw.decode("utf-8", "replace"), "bytes_base64": base64.b64encode(interp_raw).decode("ascii"), "location": location(h.p_offset, end + 1, length), "unknown_reason": None}) return { @@ -493,7 +493,7 @@ def inspect_elf(path, cache): except LayoutFailure: raise except (ELFError, ValueError, OverflowError, AssertionError, IndexError) as error: - raise LayoutFailure("format", "Selected ELF failed unchanged upstream structural parsing: " + str(error)) from error + raise LayoutFailure("malformed", "Selected ELF failed unchanged upstream structural parsing: " + str(error)) from error diff --git a/bridge/pwntools/recorded_crash_impl.py b/bridge/pwntools/recorded_crash_impl.py index 068e94cdda..82f339ab98 100644 --- a/bridge/pwntools/recorded_crash_impl.py +++ b/bridge/pwntools/recorded_crash_impl.py @@ -30,7 +30,7 @@ def encoded(value): def location(offset, size, limit): if not 0 <= offset <= limit or not 0 <= size <= limit - offset: - raise CoreFailure("format", "Recorded source range exceeds its declared container.") + raise CoreFailure("malformed", "Recorded source range exceeds its declared container.") return {"offset": hex(offset), "bytes": hex(size)} @@ -46,7 +46,7 @@ def inspect_core(path, cache): # Bytes that diverge from the ELF magic are not an ELF; a matching prefix that # ends before e_ident is complete is a truncated one. if content[:4] != b"\x7fELF"[: len(content[:4])]: - raise CoreFailure("format", "Selected recording lacks a complete ELF identification.") + raise CoreFailure("malformed", "Selected recording lacks a complete ELF identification.") if len(content) < 16: raise CoreFailure("truncated", "Selected recording lacks a complete ELF identification.") if content[4:6] != b"\x02\x01": @@ -54,9 +54,9 @@ def inspect_core(path, cache): if len(content) < 64: raise CoreFailure("truncated", "Selected ELF64 core header is truncated.") if content[6] != 1: - raise CoreFailure("format", "ELF identification version is not EV_CURRENT.") + raise CoreFailure("malformed", "ELF identification version is not EV_CURRENT.") if int.from_bytes(content[20:24], "little") != 1: - raise CoreFailure("format", "ELF header version is not EV_CURRENT.") + raise CoreFailure("malformed", "ELF header version is not EV_CURRENT.") # Linux commonly emits ELFOSABI_NONE (0), also accepted as GNU/Linux (3). # Other declared OSABIs must never select Linux note ctypes. if content[7] not in (0, 3) or content[8] != 0: @@ -87,7 +87,7 @@ def inspect_core(path, cache): header = image.header count = image.num_segments() if count and header.e_phentsize < image.structs.Elf_Phdr.sizeof(): - raise CoreFailure("format", "Program-header entry is shorter than the required ELF64 structure.") + raise CoreFailure("malformed", "Program-header entry is shorter than the required ELF64 structure.") location(header.e_phoff, count * header.e_phentsize, len(content)) segments, notes, padding, threads, signals = [], [], [], [], [] for segment_index, segment in enumerate(image.iter_segments()): @@ -98,7 +98,7 @@ def inspect_core(path, cache): if backing: location(h.p_offset, h.p_filesz, len(content)) if type_id == 1 and h.p_filesz > h.p_memsz: - raise CoreFailure("format", "Recorded PT_LOAD file bytes exceed memory size.") + raise CoreFailure("malformed", "Recorded PT_LOAD file bytes exceed memory size.") segments.append({"index": segment_index, "type": h.p_type, "type_id": type_id, "header_location": location(header_offset, header.e_phentsize, len(content)), "offset": hex(h.p_offset), "file_size": hex(h.p_filesz), "memory_size": hex(h.p_memsz), @@ -111,7 +111,7 @@ def inspect_core(path, cache): if end - position < header_size: raw = content[position:end] if any(raw): - raise CoreFailure("format", "Nonzero trailing note bytes lack a complete note header.") + raise CoreFailure("malformed", "Nonzero trailing note bytes lack a complete note header.") padding.append({"segment_index": segment_index, "location": location(position, len(raw), end), "bytes_base64": encoded(raw)}) break note = struct_parse(image.structs.Elf_Nhdr, image.stream, stream_pos=position) @@ -122,7 +122,7 @@ def inspect_core(path, cache): location(position, note_end - position, end) owner = content[owner_start:owner_start + note.n_namesz] if owner and b"\0" not in owner: - raise CoreFailure("format", "Declared note owner has no NUL terminator.") + raise CoreFailure("malformed", "Declared note owner has no NUL terminator.") display = owner.split(b"\0", 1)[0].decode("utf-8", "replace") if owner else None descriptor = content[descriptor_start:descriptor_start + note.n_descsz] note_index = len(notes) @@ -139,7 +139,7 @@ def inspect_core(path, cache): continue if note_type_id == 1: if len(descriptor) < ctypes.sizeof(prstatus_type): - raise CoreFailure("format", "Linux " + profile_label + " NT_PRSTATUS descriptor is truncated.") + raise CoreFailure("malformed", "Linux " + profile_label + " NT_PRSTATUS descriptor is truncated.") status = prstatus_type.from_buffer_copy(descriptor) registers = [] for name, kind in registers_type._fields_: @@ -148,7 +148,7 @@ def inspect_core(path, cache): threads.append({"note_index": note_index, "historical_pid": ctypes.c_int32(status.pr_pid).value, "recorded_current_signal": status.pr_cursig, "registers": registers}) elif note_type_id == 0x53494749: if len(descriptor) < ctypes.sizeof(elf_siginfo_64): - raise CoreFailure("format", "Linux " + profile_label + " NT_SIGINFO descriptor is truncated.") + raise CoreFailure("malformed", "Linux " + profile_label + " NT_SIGINFO descriptor is truncated.") signal = elf_siginfo_64.from_buffer_copy(descriptor) number = ctypes.c_int32(signal.si_signo).value code = ctypes.c_int32(signal.si_code).value @@ -168,7 +168,7 @@ def inspect_core(path, cache): except CoreFailure: raise except (ELFError, ValueError, AssertionError, IndexError) as error: - raise CoreFailure("format", "Recorded core failed unchanged upstream structural parsing: " + str(error)) from error + raise CoreFailure("malformed", "Recorded core failed unchanged upstream structural parsing: " + str(error)) from error if __name__ == "__main__": diff --git a/bridge/pwntools/test_layout.py b/bridge/pwntools/test_layout.py index db482e6b10..d526d01adb 100644 --- a/bridge/pwntools/test_layout.py +++ b/bridge/pwntools/test_layout.py @@ -189,7 +189,7 @@ class LayoutStorageTests(unittest.TestCase): with self.subTest(stride=stride): with self.assertRaises(layout["LayoutFailure"]) as raised: self.inspect("SHT_PROGBITS", 0, stride) - self.assertEqual(raised.exception.reason, "format") + self.assertEqual(raised.exception.reason, "malformed") self.assertIn("section-header entry", str(raised.exception)) for stride in (64, 96): with self.subTest(stride=stride): diff --git a/docs/guides/managed/managed-code-analysis.md b/docs/guides/managed/managed-code-analysis.md index c438eaeab2..9b079977e5 100644 --- a/docs/guides/managed/managed-code-analysis.md +++ b/docs/guides/managed/managed-code-analysis.md @@ -530,7 +530,8 @@ not an input error, in inspection and comparison: `unsupported_target` with the malformed side by its own path. `details.field` and `details.offset` give the reader's structure and byte offset when known. The arguments are not at fault, so no input recovery is offered. A metadata layout or signature form -outside decoder coverage is `unsupported_target` without `failure_kind`. +outside decoder coverage is `unsupported_target` with `details.failure_kind` +`unsupported`. Inventory status follows the same split: when a reader stops on such a form (`unsupported-metadata` or `unsupported-signature`), `metadata.status` is `partial` and an artifact's `classification.status` stays `managed`; only a diff --git a/docs/guides/native/go-binaries.md b/docs/guides/native/go-binaries.md index 6fa3279366..18eaa9313e 100644 --- a/docs/guides/native/go-binaries.md +++ b/docs/guides/native/go-binaries.md @@ -207,8 +207,8 @@ architecture table was cut short rather than corrupted: `details.failure_kind` i acquire the complete file again. A CAFEBABE file whose architecture count reads as a Java class-file version is not read as a truncated universal file. A FAT form outside REA's coverage, such as an -alignment exponent above 52, is `unsupported_target` without -`failure_kind`. The same rules apply to `inspect_rust_binary`, +alignment exponent above 52, is `unsupported_target` with `details.failure_kind` +`unsupported`. The same rules apply to `inspect_rust_binary`, `inspect_dwarf_units` and `inspect_native_initializers`. For ELF images without a named build-info section, discovery checks each diff --git a/docs/maven-gradle-metadata.md b/docs/maven-gradle-metadata.md index 94027538c2..eb24b28261 100644 --- a/docs/maven-gradle-metadata.md +++ b/docs/maven-gradle-metadata.md @@ -98,7 +98,7 @@ The selected file is limited to 1 MiB by default (16 MiB maximum). Exceeding the budget fails without partial success. Malformed XML or JSON is also `unsupported_target`, with `details.failure_kind` set to `malformed`. A well-formed document that is not a Maven project or Gradle module metadata file -is `unsupported_target` without that field. Document type declarations are +is `unsupported_target` with `details.failure_kind` set to `unsupported`. Document type declarations are unsupported. External entities are not resolved. A POM is counted as a stream before its document tree is built, and one with diff --git a/scripts/fixtures/generate-mitmproxy-capture.py b/scripts/fixtures/generate-mitmproxy-capture.py index 7bea41228e..c4eb2c795a 100644 --- a/scripts/fixtures/generate-mitmproxy-capture.py +++ b/scripts/fixtures/generate-mitmproxy-capture.py @@ -18,7 +18,7 @@ class Generator: adapter = importlib.util.module_from_spec(spec) spec.loader.exec_module(adapter) classifications = [ - (adapter.CaptureFailure("format", "Malformed retained record.", "/record"), "format"), + (adapter.CaptureFailure("malformed", "Malformed retained record.", "/record"), "malformed"), (adapter.CaptureFailure("input-limit", "Nesting budget.", "/extension"), "input-limit"), (MemoryError("payload must not enter diagnostics"), "resource-limit"), (RuntimeError("payload must not enter diagnostics"), "decoder"), @@ -28,7 +28,7 @@ class Generator: reply = adapter.failure_reply(error) assert reply["reason"] == expected, reply assert "payload must not enter diagnostics" not in json.dumps(reply) - for state, expected in [({"metadata": {1: b"bad-key"}}, "format"), ({"metadata": object()}, "decoder")]: + for state, expected in [({"metadata": {1: b"bad-key"}}, "malformed"), ({"metadata": object()}, "decoder")]: try: adapter.project_record(state, [], 64) except adapter.CaptureFailure as error: diff --git a/src/artifacts/ArtifactProvider.ts b/src/artifacts/ArtifactProvider.ts index deb76ee4de..991618fd33 100644 --- a/src/artifacts/ArtifactProvider.ts +++ b/src/artifacts/ArtifactProvider.ts @@ -49,8 +49,8 @@ import { } from "../domain/binaryTargetTypes.js"; import { AnalysisCapabilityUnavailableError, - unsupportedTarget, AnalysisTargetFailureError, + unsupportedTarget, } from "../domain/analysisErrorCore.js"; import type { JsonValue } from "../domain/jsonValue.js"; import { interfaceBuilderLimitsSchema } from "../domain/apple/interfaceBuilderGraph.js"; diff --git a/src/artifacts/ArtifactProviderTargetPath.test.ts b/src/artifacts/ArtifactProviderTargetPath.test.ts index c513f421e6..c0c9f5648a 100644 --- a/src/artifacts/ArtifactProviderTargetPath.test.ts +++ b/src/artifacts/ArtifactProviderTargetPath.test.ts @@ -28,6 +28,7 @@ it("names the bundle the caller selected, not its resolved target, in a target f expect(projectAnalysisError(result.error)).toMatchObject({ code: "unsupported_target", details: { + operation: "decode_interface_builder", path: "/fixture/Selected.app", failure_kind: "malformed", format: "nib-archive", diff --git a/src/artifacts/NativeDmgArtifactReader.ts b/src/artifacts/NativeDmgArtifactReader.ts index b102057894..86a767dbea 100644 --- a/src/artifacts/NativeDmgArtifactReader.ts +++ b/src/artifacts/NativeDmgArtifactReader.ts @@ -124,16 +124,15 @@ class NativeDmgCommandFailure extends ArtifactReaderFailure { integrityCheck: failure.reason === "integrity" ? "image-checksum" : undefined, // hdiutil's own verdict that the bytes are not a disk image it reads. - ...(failure.reason === "unsupported" - ? { - parseFailure: { + parseFailure: + failure.reason === "unsupported" + ? { kind: "unsupported", format: "dmg", detail: message, undecodedContent: false, - }, - } - : {}), + } + : undefined, }); this.processNotStarted = options?.processNotStarted ?? false; this.verifyDiagnostic = failure.verifyDiagnostic; diff --git a/src/artifacts/PyInstallerArtifactReader.ts b/src/artifacts/PyInstallerArtifactReader.ts index 4657ebc14f..aab4e07a30 100644 --- a/src/artifacts/PyInstallerArtifactReader.ts +++ b/src/artifacts/PyInstallerArtifactReader.ts @@ -390,12 +390,12 @@ export class PyInstallerArtifactReader implements ArtifactReader { const cookie = this.#admission?.cookie ?? (await this.#cookie(handle, size, signal)); state.budget = artifactExpansionBudgetBytes(cookie.packageLength); - const toc = await this.#toc(handle, cookie, signal); + const toc = await this.#toc(handle, cookie, size, signal); for (const entry of toc) { this.#charge(state, entry.uncompressedSize); this.#reserveMetadata(state, { ...entry }, false); } - const images = await this.#pyzImages(state, handle, cookie, toc); + const images = await this.#pyzImages(state, handle, cookie, size, toc); const magic = scriptPythonMagic( cookie, [...images.values()].map((image) => image.archive), @@ -485,9 +485,10 @@ export class PyInstallerArtifactReader implements ArtifactReader { async #toc( handle: FileHandle, cookie: PyInstallerCookie, + fileSize: number, signal?: AbortSignal, ): Promise { - const toc = await readCArchiveToc(handle, cookie, signal); + const toc = await readCArchiveToc(handle, cookie, signal, fileSize); if (!toc.ok) throw failure(toc.error); return toc.value; } @@ -496,6 +497,7 @@ export class PyInstallerArtifactReader implements ArtifactReader { state: ArchiveParseState, handle: FileHandle, cookie: PyInstallerCookie, + fileSize: number, toc: readonly CArchiveEntry[], ): Promise> { const { signal } = state; @@ -523,12 +525,14 @@ export class PyInstallerArtifactReader implements ArtifactReader { const source = spooled ?? { handle, start: cookie.archiveStart + entry.offset, + size: fileSize, }; const parsed = await readPyzArchive( source.handle, source.start, entry.uncompressedSize, signal, + source.size, ); if (!parsed.ok) throw failure(parsed.error); if (parsed.value.kind === "entries") diff --git a/src/artifacts/UImageArtifactReader.ts b/src/artifacts/UImageArtifactReader.ts index e90f8fcfb4..24b61c9575 100644 --- a/src/artifacts/UImageArtifactReader.ts +++ b/src/artifacts/UImageArtifactReader.ts @@ -9,6 +9,7 @@ import type { ArtifactIntegrityPolicyName } from "../domain/artifactIntegrityPol import { ArtifactReaderFailure, malformedArtifact, + truncatedArtifact, } from "../resources/index.js"; import { PositionalArtifactReader, @@ -74,8 +75,13 @@ export class UImageArtifactReader extends PositionalArtifactReader { bytes.writeBigUInt64BE(1n << 40n, 32); return bytes; })(), - "malformed", + "truncated", ], [ "a node count that cannot fit", diff --git a/src/artifacts/UnityFsStructures.ts b/src/artifacts/UnityFsStructures.ts index 13b0dd78aa..3e2ec6268e 100644 --- a/src/artifacts/UnityFsStructures.ts +++ b/src/artifacts/UnityFsStructures.ts @@ -134,7 +134,7 @@ export const readUnityFsHeader = async ( `UnityFS format ${String(facts.formatVersion)} is unsupported; ${String(UNITYFS_FORMAT_VERSION_MIN)}-${String(UNITYFS_FORMAT_VERSION_MAX)} are supported`, ); if (facts.declaredSize > BigInt(size)) - throw unityFsFormatFailure("declared size exceeds the file"); + throw unityFsTruncatedFailure("declared size exceeds the file"); if (facts.declaredSize < BigInt(facts.afterFixed)) throw unityFsFormatFailure("declared size excludes the header"); const declaredSize = Number(facts.declaredSize); diff --git a/src/artifacts/WxapkgArtifactReader.test.ts b/src/artifacts/WxapkgArtifactReader.test.ts index fa653ca478..683e7c0f33 100644 --- a/src/artifacts/WxapkgArtifactReader.test.ts +++ b/src/artifacts/WxapkgArtifactReader.test.ts @@ -226,7 +226,7 @@ describe("WxapkgArtifactReader malformed inputs", () => { buildWxapkg([{ path: "evil.bin", data: "x", size: 1 << 20 }]), async (reader) => { await expect(list(reader)).rejects.toMatchObject({ - reason: "malformed", + reason: "truncated", }); }, ); @@ -308,7 +308,7 @@ describe("WxapkgArtifactReader data region", () => { }), async (reader) => { await expect(list(reader)).rejects.toMatchObject({ - reason: "malformed", + reason: "truncated", }); }, ); @@ -426,7 +426,7 @@ describe("WxapkgArtifactReader damaged packages", () => { it("rejects a truncated package before the declared table ends", async () => { const bytes = buildWxapkg(members); await withReader(bytes.subarray(0, 30), async (reader) => { - await expect(list(reader)).rejects.toMatchObject({ reason: "malformed" }); + await expect(list(reader)).rejects.toMatchObject({ reason: "truncated" }); }); }); diff --git a/src/artifacts/WxapkgStructures.ts b/src/artifacts/WxapkgStructures.ts index b386a4edb2..79852c4003 100644 --- a/src/artifacts/WxapkgStructures.ts +++ b/src/artifacts/WxapkgStructures.ts @@ -111,7 +111,7 @@ export const readWxapkgHeader = async ( const wxapkgIndexLayoutFailure = ( failure: WxapkgIndexLayoutFailure, ): ArtifactReaderFailure => - wxapkgFormatFailure( + wxapkgTruncatedFailure( failure._tag === "DataRegionExceedsFile" ? "declared data region exceeds the file" : "declared member table exceeds the file", @@ -137,7 +137,7 @@ export const readWxapkgFileTable = async ( if (indexLayout.tableBytes > readBytes) readBytes = indexLayout.tableBytes; } if (tableStart === undefined) - throw wxapkgFormatFailure("declared member table exceeds the file"); + throw wxapkgTruncatedFailure("declared member table exceeds the file"); if (readBytes > MAX_TABLE_BYTES) throw artifactFixedLimitFailure( { diff --git a/src/artifacts/pyinstaller/CArchiveLayout.ts b/src/artifacts/pyinstaller/CArchiveLayout.ts index 3dccd9924e..e0a32e2bc2 100644 --- a/src/artifacts/pyinstaller/CArchiveLayout.ts +++ b/src/artifacts/pyinstaller/CArchiveLayout.ts @@ -141,6 +141,7 @@ export const readCArchiveToc = async ( handle: FileHandle, cookie: PyInstallerCookie, signal?: AbortSignal, + measuredEnd?: number, ): Promise> => { if (cookie.tocLength > MAX_TOC_BYTES) return err( @@ -151,6 +152,7 @@ export const readCArchiveToc = async ( ); const position = cookie.archiveStart + cookie.tocOffset; const read = await readPyInstallerBytes(handle, { + ...(measuredEnd === undefined ? {} : { measuredEnd }), position, length: cookie.tocLength, label: "CArchive table of contents", diff --git a/src/artifacts/pyinstaller/PyInstallerPyzStore.ts b/src/artifacts/pyinstaller/PyInstallerPyzStore.ts index 53ec922139..8f689c5c8c 100644 --- a/src/artifacts/pyinstaller/PyInstallerPyzStore.ts +++ b/src/artifacts/pyinstaller/PyInstallerPyzStore.ts @@ -118,7 +118,7 @@ export class PyInstallerPyzStore { archiveStart: number, entry: CArchiveEntry, signal?: AbortSignal, - ): Promise<{ handle: FileHandle; start: number }> { + ): Promise<{ handle: FileHandle; start: number; size: number }> { abortIfNeeded(signal); if (entry.compressedSize === 0) throw malformedArtifact( @@ -155,7 +155,7 @@ export class PyInstallerPyzStore { abortIfNeeded(signal); const { handle: opened, initial } = await this.#admit(path, signal); this.#images.set(opened, { path, initial }); - return { handle: opened, start: 0 }; + return { handle: opened, start: 0, size: initial.size }; } async release(handle: FileHandle): Promise { diff --git a/src/artifacts/pyinstaller/PyzArchive.test.ts b/src/artifacts/pyinstaller/PyzArchive.test.ts index ac450573f5..fda19ad583 100644 --- a/src/artifacts/pyinstaller/PyzArchive.test.ts +++ b/src/artifacts/pyinstaller/PyzArchive.test.ts @@ -7,8 +7,13 @@ import { join } from "node:path"; import { expect, it } from "vitest"; import { readPyzArchive } from "./PyzArchive.js"; +import { observePyInstallerCookie, readCArchiveToc } from "./CArchiveLayout.js"; import { createTestTempDirectory } from "../../../tests/fixtures/temporaryDirectory.js"; -import { PYTHON_39_MAGIC, pyzArchive } from "./CArchive.fixture.js"; +import { + cArchiveExecutable, + PYTHON_39_MAGIC, + pyzArchive, +} from "./CArchive.fixture.js"; it("lists modules from a supported PYZ and leaves an unknown magic opaque", async () => { const body = Buffer.from("module"); @@ -265,3 +270,66 @@ it.each([ ]); }, ); + +it("reports read-coverage integrity instead of truncation when a CArchive shrinks before reading its TOC", async () => { + const bytes = cArchiveExecutable({ + layout: "2.1", + pythonVersion: 309, + members: [ + { + name: "main", + typeCode: "s", + payload: Buffer.from("pass\n"), + compress: false, + }, + ], + }); + const root = await createTestTempDirectory("rea-pyinstaller-toc-shrink-"); + const path = join(root, "app"); + await writeFile(path, bytes); + const handle = await open(path, "r+"); + try { + const observed = await observePyInstallerCookie(handle, bytes.length); + expect(observed).toMatchObject({ ok: true, value: { state: "located" } }); + if (!observed.ok || observed.value.state !== "located") + throw new Error("Expected a located CArchive cookie"); + const { cookie } = observed.value; + await handle.truncate(cookie.archiveStart + cookie.tocOffset + 4); + await expect( + readCArchiveToc(handle, cookie, undefined, bytes.length), + ).rejects.toMatchObject({ + reason: "integrity", + integrityCheck: "read-coverage", + }); + } finally { + await handle.close(); + } +}); + +it.each([ + ["header", 4], + ["table", 12], +] as const)( + "reports read-coverage integrity instead of truncation when a PYZ shrinks before reading its %s", + async (_stage, shrunkBytes) => { + const image = pyzArchive({ + magic: PYTHON_39_MAGIC, + modules: [{ name: "app", typeCode: 0, body: Buffer.from("module body") }], + }); + const root = await createTestTempDirectory("rea-pyz-shrink-"); + const path = join(root, "image.pyz"); + await writeFile(path, image); + const handle = await open(path, "r+"); + try { + await handle.truncate(shrunkBytes); + await expect( + readPyzArchive(handle, 0, image.length, undefined, image.length), + ).rejects.toMatchObject({ + reason: "integrity", + integrityCheck: "read-coverage", + }); + } finally { + await handle.close(); + } + }, +); diff --git a/src/artifacts/pyinstaller/PyzArchive.ts b/src/artifacts/pyinstaller/PyzArchive.ts index 569fa9d90e..3f7dadccae 100644 --- a/src/artifacts/pyinstaller/PyzArchive.ts +++ b/src/artifacts/pyinstaller/PyzArchive.ts @@ -1,6 +1,9 @@ import type { FileHandle } from "node:fs/promises"; import { hashReadable } from "../ArtifactHash.js"; -import { readArtifactFileChunks } from "../../resources/index.js"; +import { + ArtifactReaderFailure, + readArtifactFileChunks, +} from "../../resources/index.js"; import { readPyInstallerBytes } from "./PyInstallerBytes.js"; import { BinaryReader } from "../../domain/binaryContainer.js"; @@ -84,12 +87,14 @@ export const readPyzArchive = async ( start: number, size: number, signal?: AbortSignal, + measuredEnd?: number, ): Promise> => { if (size < PYZ_HEADER_BYTES) return err( pyInstallerFailure("malformed", "PYZ archive magic does not match"), ); const headerRead = await readPyInstallerBytes(handle, { + ...(measuredEnd === undefined ? {} : { measuredEnd }), position: start, length: PYZ_HEADER_BYTES, label: "PYZ header", @@ -109,6 +114,7 @@ export const readPyzArchive = async ( ), ); const read = await readPyInstallerBytes(handle, { + ...(measuredEnd === undefined ? {} : { measuredEnd }), position: start + header.tocOffset, length: tableSize, label: "PYZ table", @@ -124,10 +130,17 @@ export const readPyzArchive = async ( }), signal, ); - if (digest.bytes !== size) + if (digest.bytes !== size) { + if (measuredEnd !== undefined && start + size <= measuredEnd) + throw new ArtifactReaderFailure( + "integrity", + "PYZ image ended before the measured file size", + { integrityCheck: "read-coverage" }, + ); return err( pyInstallerFailure("malformed", "PYZ image extends outside the file"), ); + } return parsePyzParts(header, table, digest.sha256); }; diff --git a/src/browser/history/CaptureFormatError.ts b/src/browser/history/CaptureFormatError.ts index 41a49ac052..b992d7fd4b 100644 --- a/src/browser/history/CaptureFormatError.ts +++ b/src/browser/history/CaptureFormatError.ts @@ -154,7 +154,7 @@ export class CaptureFormatError extends ParseFailureError< /** The reason a decoder child reports for this failure on the reply wire. */ get replyReason(): - | "format" + | "malformed" | "unsupported" | "decoder" | "input-limit" @@ -163,7 +163,7 @@ export class CaptureFormatError extends ParseFailureError< if (this.ceiling !== undefined) return "fixed-limit"; const { limit } = this; if (limit === undefined) - return this.failure.kind === "unsupported" ? "unsupported" : "format"; + return this.failure.kind === "unsupported" ? "unsupported" : "malformed"; return CAPTURE_LIMITS[limit.name].reply ?? "decoder"; } } diff --git a/src/browser/history/HistoricalCaptureDecoder.ts b/src/browser/history/HistoricalCaptureDecoder.ts index 8f03de084f..a206ad5f53 100644 --- a/src/browser/history/HistoricalCaptureDecoder.ts +++ b/src/browser/history/HistoricalCaptureDecoder.ts @@ -253,7 +253,7 @@ export class HistoricalCaptureDecoder { encodedReplyBytes = decodedReply.bytes; replyFinalization = decodedReply.finalization; if (!reply.ok) { - if (reply.reason === "format") + if (reply.reason === "malformed") throw new AnalysisInputError(OPERATION, undefined, [ { path: ["capture_path", reply.pointer], diff --git a/src/browser/history/HistoricalCaptureReply.ts b/src/browser/history/HistoricalCaptureReply.ts index 346c0de8a0..35425fa2ba 100644 --- a/src/browser/history/HistoricalCaptureReply.ts +++ b/src/browser/history/HistoricalCaptureReply.ts @@ -33,7 +33,7 @@ const replySchema = z.discriminatedUnion("ok", [ z.strictObject({ ok: z.literal(false), reason: z.enum([ - "format", + "malformed", "unsupported", "input-limit", "expanded-limit", diff --git a/src/cli/projectCliAnalysisResult.ts b/src/cli/projectCliAnalysisResult.ts index 01867a5e62..aca5f2a7f3 100644 --- a/src/cli/projectCliAnalysisResult.ts +++ b/src/cli/projectCliAnalysisResult.ts @@ -2,6 +2,19 @@ import type { z } from "zod"; import { recordedControlSchemas } from "../domain/analysisSettingDefinitions.js"; import type { JsonValue } from "../domain/jsonValue.js"; +import { + MCP_TARGET_FAILURE_SPELLING, + renderTargetFailureRecovery, + TARGET_FAILURE_KINDS, + type TargetFailureKind, + type TargetFailureRecoveryFacts, + type TargetFailureSpelling, +} from "../domain/targetFailure.js"; +import { + MCP_INPUT_SCHEMA_SPELLING, + renderInputSchemaRemediation, + type InputSchemaRemediationSpelling, +} from "../domain/analysisErrorPresentation.js"; import type { Result } from "../domain/result.js"; import { cliCommandForOperation, @@ -80,6 +93,7 @@ export const projectCliInputFields = ( ? [{ name: binding.operation, flags: binding.flags }] : orderedOperations(binding.operations, error.details.operation); const issues = renamedIssues(error, error.details, binding); + const remediation = cliConflictRemediation(error, error.details, binding); const inputs = renamedTargetInputs(error.details, binding); const limit = flaggedLimit(error.details.limit, operations); const relatedFlags = @@ -89,6 +103,7 @@ export const projectCliInputFields = ( : relatedCliFlagsFromOperations(error.details, operations); if ( issues === undefined && + remediation === undefined && inputs === undefined && limit === undefined && relatedFlags === undefined @@ -96,6 +111,7 @@ export const projectCliInputFields = ( return output; return { ...error, + ...(remediation === undefined ? {} : { remediation }), details: { ...error.details, ...(issues === undefined ? {} : { issues }), @@ -156,15 +172,20 @@ const projectErrorRecord = ( details.secondary_failures, context, ); + const remediation = + cliTargetFailureRemediation(error, details, context) ?? + cliInputSchemaRemediation(error, details, context); if ( limit === undefined && relatedFlags === undefined && relatedCommands === undefined && - secondaryFailures === undefined + secondaryFailures === undefined && + remediation === undefined ) return error; return { ...error, + ...(remediation === undefined ? {} : { remediation }), details: { ...details, ...(limit === undefined ? {} : { limit }), @@ -181,6 +202,193 @@ const projectErrorRecord = ( }; }; +const stringList = (value: JsonValue | undefined): string[] => + Array.isArray(value) + ? value.filter((item): item is string => typeof item === "string") + : []; + +const isTargetFailureKind = ( + value: JsonValue | undefined, +): value is TargetFailureKind => + typeof value === "string" && + (TARGET_FAILURE_KINDS as readonly string[]).includes(value); + +const targetInputFields = (details: Record): string[] => + Array.isArray(details.inputs) + ? details.inputs.flatMap((input) => + isObject(input) && typeof input.field === "string" ? [input.field] : [], + ) + : []; + +/** + * Rewrite a conflict failure's recovery text with CLI input spellings before + * `renamedTargetInputs` replaces the source field names in `details.inputs`. + */ +const cliConflictRemediation = ( + error: Record, + details: Record, + binding: CliInputFieldBinding, +): Record | undefined => { + const { remediation } = error; + if ( + details.operation !== binding.operation || + details.failure_kind !== "conflict" || + typeof details.format !== "string" || + !isObject(remediation) || + typeof remediation.action !== "string" + ) + return undefined; + const inputFields = targetInputFields(details); + if (inputFields.length === 0) return undefined; + const mcpFacts: TargetFailureRecoveryFacts = { + operation: binding.operation, + kind: "conflict", + format: details.format, + inputFields, + }; + const mcp = renderTargetFailureRecovery( + mcpFacts, + MCP_TARGET_FAILURE_SPELLING, + ); + if (!remediation.action.startsWith(mcp)) return undefined; + const cliInputFields = inputFields.map((field) => { + const flag = cliFlagForFlags(field, binding.flags); + if (flag !== undefined) return flag; + return Object.hasOwn(binding.fields, field) + ? (binding.fields[field] ?? field) + : field; + }); + const cli = renderTargetFailureRecovery( + { ...mcpFacts, inputFields: cliInputFields }, + MCP_TARGET_FAILURE_SPELLING, + ); + return cli === mcp + ? undefined + : { + ...remediation, + action: `${cli}${remediation.action.slice(mcp.length)}`, + }; +}; + +/** + * A target failure's recovery in CLI spelling: the projection table renders + * the same facts with commands and options in place of MCP tool names. Only + * the table's own MCP text is replaced, so appended guidance survives. + */ +const cliTargetFailureRemediation = ( + error: Record, + details: Record, + context: CliCommandOutputProjectionContext, +): Record | undefined => { + const { remediation, retry } = error; + // `io` is the only kind whose table text depends on the retry hint. + // cleanup_incomplete keeps the target recovery and drops `retry`, so the + // other kinds still rewrite when the action starts with that table text. + if ( + !isObject(remediation) || + typeof remediation.action !== "string" || + !isTargetFailureKind(details.failure_kind) || + typeof details.format !== "string" || + typeof details.operation !== "string" || + (details.failure_kind === "io" && typeof retry !== "string") + ) + return undefined; + const inputFields = targetInputFields(details); + const facts: TargetFailureRecoveryFacts = { + operation: details.operation, + kind: details.failure_kind, + format: details.format, + inputFields, + transient: retry === "backoff", + alternatives: { + operations: stringList(details.related_operations), + providers: stringList(details.related_providers), + }, + }; + const mcp = renderTargetFailureRecovery(facts, MCP_TARGET_FAILURE_SPELLING); + if (!remediation.action.startsWith(mcp)) return undefined; + const cliName = context.cliName ?? "rea"; + const mappedOperation = (operation: string): string | undefined => + cliCommandForOperation( + operation, + context.commands, + cliName, + context.recordedCommands, + ); + const spelling: TargetFailureSpelling = { + operation: (operation) => mappedOperation(operation) ?? operation, + provider: (providerId) => `--provider ${providerId}`, + }; + const operations = orderedOperations(context.operations, details.operation); + const cliInputFields = inputFields.map( + (field) => cliFlagForOperations(field, operations) ?? field, + ); + const cliOperations = facts.alternatives?.operations?.filter( + (operation) => mappedOperation(operation) !== undefined, + ); + const cliProviders = facts.alternatives?.providers; + const cliFacts: TargetFailureRecoveryFacts = { + ...facts, + inputFields: cliInputFields, + alternatives: { + ...(cliOperations === undefined ? {} : { operations: cliOperations }), + ...(cliProviders === undefined ? {} : { providers: cliProviders }), + }, + }; + const cli = renderTargetFailureRecovery(cliFacts, spelling); + return cli === mcp + ? undefined + : { + ...remediation, + action: `${cli}${remediation.action.slice(mcp.length)}`, + }; +}; + +/** + * An input refusal's recovery in CLI spelling. Presentation renders the MCP + * sentence from the same facts; this replaces that rendering with the command + * and drops the catalog-refresh clause. A prefixed argument hint stays ahead + * of the sentence. + */ +const cliInputSchemaRemediation = ( + error: Record, + details: Record, + context: CliCommandOutputProjectionContext, +): Record | undefined => { + const { remediation } = error; + if ( + typeof details.operation !== "string" || + !isObject(remediation) || + typeof remediation.action !== "string" + ) + return undefined; + const operation = details.operation; + const mcp = renderInputSchemaRemediation( + operation, + MCP_INPUT_SCHEMA_SPELLING, + ); + const index = remediation.action.indexOf(mcp); + if (index < 0) return undefined; + const command = cliCommandForOperation( + operation, + context.commands, + context.cliName ?? "rea", + context.recordedCommands, + ); + if (command === undefined) return undefined; + const spelling: InputSchemaRemediationSpelling = { + subject: () => command, + includeCatalogRefresh: false, + }; + const cli = renderInputSchemaRemediation(operation, spelling); + return cli === mcp + ? undefined + : { + ...remediation, + action: `${remediation.action.slice(0, index)}${cli}${remediation.action.slice(index + mcp.length)}`, + }; +}; + const projectedSecondaryFailures = ( secondary: JsonValue | undefined, context: CliCommandOutputProjectionContext, diff --git a/src/domain/analysisErrorPresentation.ts b/src/domain/analysisErrorPresentation.ts index 2e19db932f..f5c356b6e1 100644 --- a/src/domain/analysisErrorPresentation.ts +++ b/src/domain/analysisErrorPresentation.ts @@ -53,6 +53,34 @@ import { } from "./analysisErrorBase.js"; import type { AnalysisErrorProjection } from "./analysisErrorProjection.js"; +/** + * How one adapter names the operation in an input-schema refusal. MCP names + * the tool and tells the client to refresh its catalog. The CLI names the + * command and omits that client-only clause. + */ +export interface InputSchemaRemediationSpelling { + readonly subject: (operation: string) => string; + readonly includeCatalogRefresh: boolean; +} + +/** The MCP spelling, which is also the adapter-independent one in Evidence. */ +export const MCP_INPUT_SCHEMA_SPELLING: InputSchemaRemediationSpelling = { + subject: (operation) => operation, + includeCatalogRefresh: true, +}; + +/** The input-schema refusal, in one adapter's spelling. */ +export const renderInputSchemaRemediation = ( + operation: string, + spelling: InputSchemaRemediationSpelling, +): string => { + const subject = spelling.subject(operation); + const refresh = spelling.includeCatalogRefresh + ? "; if using MCP and the catalog may be stale, call tools/list" + : ""; + return `Read the declared input schema or CLI usage for ${subject}${refresh}. Correct the listed fields, then retry. Do not repeat the unchanged call.`; +}; + /** Explain how to preserve an observation the session could not retain. */ export const UNRETAINED_EVIDENCE_EXPORT_GUIDANCE = "Unretained Evidence is not included in the exported investigation; if present in this response, save it separately."; @@ -247,7 +275,7 @@ export const analysisErrorRemediationAction = ( ); const baseAction = error.remediationAction ?? - `Read the declared input schema or CLI usage for ${error.operation}; if using MCP and the catalog may be stale, call tools/list. Correct the listed fields, then retry. Do not repeat the unchanged call.`; + renderInputSchemaRemediation(error.operation, MCP_INPUT_SCHEMA_SPELLING); return mistakeRemediation === undefined ? baseAction : `${mistakeRemediation} ${baseAction}`; diff --git a/src/evm/EvmProducerLimits.test.ts b/src/evm/EvmProducerLimits.test.ts index 86f692caa4..3c8975f4c6 100644 --- a/src/evm/EvmProducerLimits.test.ts +++ b/src/evm/EvmProducerLimits.test.ts @@ -60,5 +60,8 @@ it("recovers complete EVMole worker evidence for the same carrier after raising }); // A larger resource budget does not change the explicitly selected encoding contract. await writeFile(snapshot, "0xzz"); - expect(await inspect(4096, 2)).toMatchObject({ ok: false, reason: "format" }); + expect(await inspect(4096, 2)).toMatchObject({ + ok: false, + reason: "malformed", + }); }); diff --git a/src/evm/EvmoleInterfaceProvider.ts b/src/evm/EvmoleInterfaceProvider.ts index ff66912c68..bfc6b68f6d 100644 --- a/src/evm/EvmoleInterfaceProvider.ts +++ b/src/evm/EvmoleInterfaceProvider.ts @@ -51,7 +51,6 @@ import { import { type AnalysisCancelledError, AnalysisCapabilityUnavailableError, - AnalysisInputError, AnalysisTargetFailureError, AnalysisOutputError, cancelledBy, @@ -265,7 +264,7 @@ const replySchema = z.discriminatedUnion("ok", [ }), z.strictObject({ ok: z.literal(false), - reason: z.enum(["format", "decoder", "output-limit", "unsupported"]), + reason: z.enum(["malformed", "decoder", "output-limit", "unsupported"]), message: z.string(), }), ]); @@ -767,7 +766,7 @@ export class EvmoleInterfaceProvider implements EvmInterfacePort { { capturedOutput }, ); // The worker rejected the selected bytecode, not the request. - if (reply.reason === "format") + if (reply.reason === "malformed") throw new AnalysisTargetFailureError( OPERATION, input.path, diff --git a/src/evm/EvmoleInterfaceWorker.ts b/src/evm/EvmoleInterfaceWorker.ts index e5187ea200..bd01c48d9e 100644 --- a/src/evm/EvmoleInterfaceWorker.ts +++ b/src/evm/EvmoleInterfaceWorker.ts @@ -94,7 +94,7 @@ const main = async (): Promise => { ok: false, reason: cause instanceof EvmCarrierFailure - ? "format" + ? "malformed" : cause instanceof UnsupportedContainer ? "unsupported" : "decoder", diff --git a/src/javascript/sourceMaps/SourceMapCodecProcess.ts b/src/javascript/sourceMaps/SourceMapCodecProcess.ts index e6fce95481..1771b334b2 100644 --- a/src/javascript/sourceMaps/SourceMapCodecProcess.ts +++ b/src/javascript/sourceMaps/SourceMapCodecProcess.ts @@ -70,7 +70,7 @@ const execute = async (): Promise => { !isSourceMapFailure(cause) || cause.kind === "malformed" || cause.kind === "truncated" - ? "format" + ? "malformed" : cause.kind, message: cause.message, }); diff --git a/src/javascript/sourceMaps/SourceMapCodecProtocol.ts b/src/javascript/sourceMaps/SourceMapCodecProtocol.ts index b3034be777..4d339d1949 100644 --- a/src/javascript/sourceMaps/SourceMapCodecProtocol.ts +++ b/src/javascript/sourceMaps/SourceMapCodecProtocol.ts @@ -19,7 +19,7 @@ export const sourceMapCodecReplySchema = z.discriminatedUnion("state", [ }), z.strictObject({ state: z.literal("failure"), - reason: z.enum(["format", "unsupported", "limit"]), + reason: z.enum(["malformed", "unsupported", "limit"]), message: z.string(), }), ]); diff --git a/src/javascript/sourceMaps/SourceMapReply.ts b/src/javascript/sourceMaps/SourceMapReply.ts index d3f613a3fa..166494f196 100644 --- a/src/javascript/sourceMaps/SourceMapReply.ts +++ b/src/javascript/sourceMaps/SourceMapReply.ts @@ -78,7 +78,7 @@ const codecRuntimeFailure = ( const codecFailure = ( path: string, - reason: "format" | "unsupported" | "limit", + reason: "malformed" | "unsupported" | "limit", detail: string, ): Result => err( diff --git a/src/native/NativeMachoSource.ts b/src/native/NativeMachoSource.ts index c62ac059f9..d0989757a0 100644 --- a/src/native/NativeMachoSource.ts +++ b/src/native/NativeMachoSource.ts @@ -45,7 +45,7 @@ export class NativeMachoSourceVerificationFailure extends ArtifactReaderFailure ? {} : { cancellation: verificationCause.cancellation }), } - : { integrityCheck: undefined }), + : { integrityCheck: undefined, parseFailure: undefined }), }, verificationCause instanceof ArtifactReaderFailure ? verificationCause.details diff --git a/src/native/pwndbg/PwndbgCoreContext.ts b/src/native/pwndbg/PwndbgCoreContext.ts index 86823b1c02..56bd41dd12 100644 --- a/src/native/pwndbg/PwndbgCoreContext.ts +++ b/src/native/pwndbg/PwndbgCoreContext.ts @@ -52,13 +52,7 @@ const replySchema = z.discriminatedUnion("ok", [ z.strictObject({ ok: z.literal(true), value: recordedCrashDebuggerSchema }), z.strictObject({ ok: z.literal(false), - reason: z.enum([ - "unavailable", - "unsupported", - "decoder", - "format", - "output-limit", - ]), + reason: z.enum(["unavailable", "unsupported", "decoder", "output-limit"]), message: z.string(), }), ]); @@ -314,13 +308,11 @@ export const inspectPwndbgCore = async ({ ), finalization, ); - if (reply.reason === "format" || reply.reason === "output-limit") + if (reply.reason === "output-limit") throw pwndbgContextFinalizationFailure( new AnalysisOutputError(OPERATION, reply.message, { capturedOutput: recordedCrashStageOutput(diagnostics, output), - ...(reply.reason === "output-limit" - ? pwntoolsReplyOutputLimit(producerLimits) - : {}), + ...pwntoolsReplyOutputLimit(producerLimits), }), finalization, ); diff --git a/src/native/pwntools/PwntoolsDecoder.ts b/src/native/pwntools/PwntoolsDecoder.ts index 782dbe6449..0e916a923e 100644 --- a/src/native/pwntools/PwntoolsDecoder.ts +++ b/src/native/pwntools/PwntoolsDecoder.ts @@ -45,7 +45,6 @@ import type { import { AnalysisError } from "../../domain/analysisErrorBase.js"; import { AnalysisCapabilityUnavailableError, - AnalysisInputError, AnalysisTargetFailureError, AnalysisOutputError, AnalysisResourceConstraintError, @@ -322,7 +321,7 @@ export class PwntoolsDecoder< z.strictObject({ ok: z.literal(false), reason: z.enum([ - "format", + "malformed", "truncated", "unsupported", "unsupported-target", @@ -598,25 +597,14 @@ export class PwntoolsDecoder< remediationAction: `Review reported limits and available host memory; allocation failure alone does not prove exhaustion. ${pwntoolsBudgetRecovery(producerLimits)}`, }, ); - // The worker's ELF owner measured the end inside a declared header. - if (reply.reason === "truncated") + // The worker's ELF owner raised the kind: bytes that break the + // format, or end inside a header it measured. + if (reply.reason === "malformed" || reply.reason === "truncated") throw new AnalysisTargetFailureError( OPERATION, input.path, { - kind: "truncated", - format: this.profile.targetFormat, - detail: reply.message, - }, - { capturedOutput }, - ); - // The worker's ELF owner rejected the selected file's bytes. - if (reply.reason === "format") - throw new AnalysisTargetFailureError( - OPERATION, - input.path, - { - kind: "malformed", + kind: reply.reason, format: this.profile.targetFormat, detail: reply.message, }, diff --git a/src/process/OwnedLease.ts b/src/process/OwnedLease.ts index 9d57b116ee..742fe87d6d 100644 --- a/src/process/OwnedLease.ts +++ b/src/process/OwnedLease.ts @@ -63,9 +63,9 @@ export class OwnedLeaseCleanupFailure extends ArtifactReaderFailure { failure: ArtifactReaderFailure, ) { super(failure.reason, failure.message, { + ...failure.primaryFacts(), cause: primary, cleanup: failure.cleanup, - integrityCheck: failure.integrityCheck, }); this.cleanupLeases = failure.cleanupLeases; } diff --git a/src/sqlite/SqliteDatabaseSnapshot.ts b/src/sqlite/SqliteDatabaseSnapshot.ts index 2032def111..f2fb1d96aa 100644 --- a/src/sqlite/SqliteDatabaseSnapshot.ts +++ b/src/sqlite/SqliteDatabaseSnapshot.ts @@ -418,17 +418,24 @@ const verifyInactiveJournal = async ( if ( before.size !== 0n && (bytesRead !== header.length || header.some((byte) => byte !== 0)) - ) + ) { + if (phase === "initial") { + const detail = `Rollback journal may require recovery: ${path}. Supply a clean offline snapshot; only empty journals or a fully zeroed header are supported.`; + throw new ArtifactReaderFailure("unsupported", detail, { + parseFailure: { + kind: "unsupported", + format: "sqlite", + detail, + undecodedContent: true, + }, + }); + } throw new ArtifactReaderFailure( - phase === "initial" ? "unsupported" : "integrity", - phase === "initial" - ? `Rollback journal may require recovery: ${path}. Supply a clean offline snapshot; only empty journals or a fully zeroed header are supported.` - : `Rollback journal became active or malformed during database acquisition: ${path}`, - { - integrityCheck: - phase === "initial" ? undefined : "container-identity", - }, + "integrity", + `Rollback journal became active or malformed during database acquisition: ${path}`, + { integrityCheck: "container-identity" }, ); + } }, ); }; diff --git a/src/uefi/UefiAnalysisProvider.ts b/src/uefi/UefiAnalysisProvider.ts index 3af870fce5..628c8bc6d3 100644 --- a/src/uefi/UefiAnalysisProvider.ts +++ b/src/uefi/UefiAnalysisProvider.ts @@ -817,7 +817,7 @@ export class UefiAnalysisProvider implements UefiAnalysisPort { if (consumedBytes !== payload.length) return { ok: false, - reason: "format", + reason: "malformed", message: `AMD zlib stream used ${consumedBytes} of ${payload.length} declared compressed bytes.`, }; return { diff --git a/src/uefi/UefiLzmaProtocol.ts b/src/uefi/UefiLzmaProtocol.ts index ee0d4ed049..625723d9af 100644 --- a/src/uefi/UefiLzmaProtocol.ts +++ b/src/uefi/UefiLzmaProtocol.ts @@ -6,7 +6,11 @@ import { digestSchema } from "../domain/digests.js"; import { UEFI_FIRMWARE_LIMITS } from "../domain/uefi/uefiLimits.js"; import { UefiLzmaByteQueue } from "./UefiLzmaByteQueue.js"; -const decodeFailureReasonSchema = z.enum(["format", "decoder", "output-limit"]); +const decodeFailureReasonSchema = z.enum([ + "malformed", + "decoder", + "output-limit", +]); export type UefiDecodeFailureReason = z.infer; export const LZMA_FRAME_HEADER_BYTES = 8; diff --git a/src/uefi/UefiLzmaWorker.ts b/src/uefi/UefiLzmaWorker.ts index dde695d48f..24b9e1dafa 100644 --- a/src/uefi/UefiLzmaWorker.ts +++ b/src/uefi/UefiLzmaWorker.ts @@ -194,7 +194,7 @@ const decodeStreamPayload = ( ? "decoder" : failure.kind === "limit" ? "output-limit" - : "format", + : "malformed", message: errorMessage(cause), }, }; diff --git a/tests/acceptance/applications/adbErrorIdentity.test.ts b/tests/acceptance/applications/adbErrorIdentity.test.ts index d3b126c5d9..9252f3f804 100644 --- a/tests/acceptance/applications/adbErrorIdentity.test.ts +++ b/tests/acceptance/applications/adbErrorIdentity.test.ts @@ -3,6 +3,10 @@ import { join } from "node:path"; import { expect } from "vitest"; +import { + expectAdapterErrorParity, + parseMcpToolError, +} from "../../fixtures/mcpToolError.js"; import { connectLocalToolsMcp } from "../../fixtures/localToolsMcp.js"; import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; import { cliTest } from "../../support/cli/cliFixture.js"; @@ -86,10 +90,11 @@ process.exit(1); device_path: devicePath, ...transfer.input, }); - expect(reply.isError).toBe(true); - const content = reply.content.find((item) => item.type === "text"); - if (content?.type !== "text") throw new Error("Missing error response"); - expect(JSON.parse(content.text)).toEqual({ error: output.json }); + expectAdapterErrorParity( + parseMcpToolError(reply).error, + output.json, + scenario.operation, + ); await client.ping(); } expect(await readFile(source, "utf8")).toBe("caller bytes"); diff --git a/tests/acceptance/applications/peResources.test.ts b/tests/acceptance/applications/peResources.test.ts index 73d132ddcd..44bc8031cd 100644 --- a/tests/acceptance/applications/peResources.test.ts +++ b/tests/acceptance/applications/peResources.test.ts @@ -10,7 +10,10 @@ import { peResourcesSchema } from "../../../src/domain/native/peResources.js"; import { peResourceFixture } from "../../../src/domain/pe/peResources.fixture.js"; import { connectLocalToolsMcp } from "../../fixtures/localToolsMcp.js"; import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; -import { parseMcpToolError } from "../../fixtures/mcpToolError.js"; +import { + expectAdapterErrorParity, + parseMcpToolError, +} from "../../fixtures/mcpToolError.js"; import { cliTest, type TestCli } from "../../support/cli/cliFixture.js"; type PeResourceCall = ( @@ -53,7 +56,11 @@ const expectPeInputFailureAcrossAdapters = async (input: { const response = await call({ path }); expect(response.isError).toBe(true); expect(response.structuredContent).toBeUndefined(); - expect(parseMcpToolError(response)).toEqual({ error: result.json }); + expectAdapterErrorParity( + parseMcpToolError(response).error, + result.json, + "inspect_pe_resources", + ); }; const expectPeInputFailuresAcrossAdapters = async (input: { diff --git a/tests/acceptance/binaryHardeningCli.test.ts b/tests/acceptance/binaryHardeningCli.test.ts index 539eeb89cd..70649e7d3d 100644 --- a/tests/acceptance/binaryHardeningCli.test.ts +++ b/tests/acceptance/binaryHardeningCli.test.ts @@ -7,7 +7,10 @@ import { peHardeningImage, } from "../../src/native/hardening/BinaryHardening.fixture.js"; import { createTestTempDirectory } from "../fixtures/temporaryDirectory.js"; -import { parseMcpToolError } from "../fixtures/mcpToolError.js"; +import { + expectAdapterErrorParity, + parseMcpToolError, +} from "../fixtures/mcpToolError.js"; import { cliTest } from "../support/cli/cliFixture.js"; const states = ( @@ -87,6 +90,10 @@ cliTest( }); const response = await call("inspect_binary_hardening", { path: foreign }); expect(response.isError).toBe(true); - expect(parseMcpToolError(response)).toEqual({ error: rejected.json }); + expectAdapterErrorParity( + parseMcpToolError(response).error, + rejected.json, + "inspect_binary_hardening", + ); }, ); diff --git a/tests/acceptance/flutterAnalysis.test.ts b/tests/acceptance/flutterAnalysis.test.ts index d8f73ca233..df582e3e9a 100644 --- a/tests/acceptance/flutterAnalysis.test.ts +++ b/tests/acceptance/flutterAnalysis.test.ts @@ -23,7 +23,10 @@ import { import { lazyLocalToolsMcp } from "../fixtures/localToolsMcp.js"; import { createMcpSchemaValidation } from "../fixtures/mcpSchemaValidation.js"; import { expectCliMcpEvidenceParity } from "../fixtures/cliMcpEvidenceParity.js"; -import { parseMcpToolError } from "../fixtures/mcpToolError.js"; +import { + expectAdapterErrorParity, + parseMcpToolError, +} from "../fixtures/mcpToolError.js"; import { cliTest } from "../support/cli/cliFixture.js"; const connectLocalToolsMcp = lazyLocalToolsMcp(); @@ -317,7 +320,7 @@ cliTest( }); expect(result.exitCode).toBe(1); const mcp = parseMcpToolError(await call(name, { path: duplicate })); - expect(mcp.error).toEqual(result.json); + expectAdapterErrorParity(mcp.error, result.json, name); expect(mcp.error).toMatchObject({ code: "invalid_request", details: { issues: [{ message: expect.stringContaining(duplicate) }] }, diff --git a/tests/acceptance/goBinaryPointerMappingsCli.test.ts b/tests/acceptance/goBinaryPointerMappingsCli.test.ts index 6505c5b36c..1b24df307c 100644 --- a/tests/acceptance/goBinaryPointerMappingsCli.test.ts +++ b/tests/acceptance/goBinaryPointerMappingsCli.test.ts @@ -62,7 +62,14 @@ cliTest( }, }); const response = await call("inspect_go_binary", { path }); - expect(parseMcpToolError(response)).toEqual({ error: rejected.json }); + const mcpError = parseMcpToolError(response).error; + const cliError = rejected.json as typeof mcpError; + expect({ ...mcpError, remediation: undefined }).toEqual({ + ...cliError, + remediation: undefined, + }); + expect(cliError.remediation.action).toContain("rea inspect-go-binary"); + expect(mcpError.remediation.action).toContain("inspect_go_binary"); await client.ping(); }, ); diff --git a/tests/acceptance/il2cppMetadataCli.test.ts b/tests/acceptance/il2cppMetadataCli.test.ts index cb0152c6a5..6fadddb3e2 100644 --- a/tests/acceptance/il2cppMetadataCli.test.ts +++ b/tests/acceptance/il2cppMetadataCli.test.ts @@ -1103,8 +1103,16 @@ cliTest( tokenBeyondModule.writeUInt32LE(0x06000004, tokenAt(0)); const pairConflict = (reason: string) => - (path: string, binaryPath: string, binaryField: string) => ({ + ( + path: string, + binaryPath: string, + binaryField: string, + binaryRecoveryField: string, + ) => ({ code: "input_conflict", + remediation: { + action: expect.stringContaining(`(path, ${binaryRecoveryField})`), + }, details: { failure_kind: "conflict", path, @@ -1193,7 +1201,7 @@ cliTest( }); expect(result.exitCode, name).toBe(1); expect(result.json, name).toMatchObject( - expected(path, binaryPath, "binary"), + expected(path, binaryPath, "binary", "--binary"), ); const response = await call("inspect_il2cpp_metadata", { path, @@ -1201,7 +1209,7 @@ cliTest( ...(universal ? { binary_architecture: "arm64" } : {}), }); expect(parseMcpToolError(response).error, name).toMatchObject( - expected(path, binaryPath, "binary_path"), + expected(path, binaryPath, "binary_path", "binary_path"), ); } await client.ping(); diff --git a/tests/acceptance/peCertificatesCli.test.ts b/tests/acceptance/peCertificatesCli.test.ts index 7af12d0e9b..2eb93875a1 100644 --- a/tests/acceptance/peCertificatesCli.test.ts +++ b/tests/acceptance/peCertificatesCli.test.ts @@ -10,7 +10,10 @@ import { pkcs7SignedDataIndefiniteEnvelopeFixture, } from "../../src/native/pe/PeCertificates.fixture.js"; import { repeatedCertificateSignedData } from "../fixtures/peCertificateAllowance.js"; -import { parseMcpToolError } from "../fixtures/mcpToolError.js"; +import { + expectAdapterErrorParity, + parseMcpToolError, +} from "../fixtures/mcpToolError.js"; import { createTestTempDirectory } from "../fixtures/temporaryDirectory.js"; import { cliTest } from "../support/cli/cliFixture.js"; @@ -231,7 +234,9 @@ cliTest( }); const call = await cli.sharedMcpCall!(); const response = await call("inspect_pe_certificates", { path }); - expect(parseMcpToolError(response).error).toEqual(result.json); + const mcpError = parseMcpToolError(response).error; + expect(mcpError.remediation.action).toContain("inspect_pe_certificates"); + expectAdapterErrorParity(mcpError, result.json, "inspect_pe_certificates"); expect(response.structuredContent).toBeUndefined(); expect((await readFile(path)).equals(bytes)).toBe(true); }, diff --git a/tests/acceptance/peUnwindRangesCli.test.ts b/tests/acceptance/peUnwindRangesCli.test.ts index e4cbe5c796..f32819b0ca 100644 --- a/tests/acceptance/peUnwindRangesCli.test.ts +++ b/tests/acceptance/peUnwindRangesCli.test.ts @@ -8,7 +8,10 @@ import { unwindInfo, } from "../../src/native/pe/PeUnwindRanges.fixture.js"; import { createTestTempDirectory } from "../fixtures/temporaryDirectory.js"; -import { parseMcpToolError } from "../fixtures/mcpToolError.js"; +import { + expectAdapterErrorParity, + parseMcpToolError, +} from "../fixtures/mcpToolError.js"; import { cliTest } from "../support/cli/cliFixture.js"; const primary = { begin: 0x1000, end: 0x1100, unwind: 0x2000 }; @@ -83,6 +86,10 @@ cliTest( path: truncated, }); expect(mcpRefused.isError).toBe(true); - expect(parseMcpToolError(mcpRefused)).toEqual({ error: refused.json }); + expectAdapterErrorParity( + parseMcpToolError(mcpRefused).error, + refused.json, + "inspect_pe_unwind_ranges", + ); }, ); diff --git a/tests/acceptance/targetFailureConformance.test.ts b/tests/acceptance/targetFailureConformance.test.ts index 0a0b72765b..38ffecf8f5 100644 --- a/tests/acceptance/targetFailureConformance.test.ts +++ b/tests/acceptance/targetFailureConformance.test.ts @@ -50,6 +50,11 @@ for (const { operation, session, cases } of await loadTargetFailureReaders()) { expect(result.json).not.toHaveProperty("recovery"); expect(result.json).not.toHaveProperty("details.issues"); expect(result.json).not.toHaveProperty("details.format_failure"); + // The CLI names operations by command, never by MCP tool name. + expect( + (result.json as { remediation: { action: string } }).remediation + .action, + ).not.toContain(operation); const call = await cli.sharedMcpCall!(); if (session === true) { diff --git a/tests/acceptance/webArtifactErrorProvenance.test.ts b/tests/acceptance/webArtifactErrorProvenance.test.ts index 1745c907eb..c93e7f6856 100644 --- a/tests/acceptance/webArtifactErrorProvenance.test.ts +++ b/tests/acceptance/webArtifactErrorProvenance.test.ts @@ -4,7 +4,10 @@ import { dirname, join } from "node:path"; import { expect } from "vitest"; import { lazyLocalToolsMcp } from "../fixtures/localToolsMcp.js"; -import { parseMcpToolError } from "../fixtures/mcpToolError.js"; +import { + expectAdapterErrorParity, + parseMcpToolError, +} from "../fixtures/mcpToolError.js"; import { createTestTempDirectory } from "../fixtures/temporaryDirectory.js"; import { webModuleArtifactsFixture } from "../fixtures/webModuleTrace.js"; import { cliTest } from "../support/cli/cliFixture.js"; @@ -119,26 +122,25 @@ cliTest( await call(selection.operation, selection.input), ); for (const error of [response.json, mcp.error]) - expect(error).toMatchObject({ - code: - reason === "malformed" - ? "unsupported_target" - : "artifact_operation_failed", - // A malformed captured source is a target failure on that file; - // an escaping manifest path is an artifact operation refusal. - details: - reason === "malformed" - ? { + expect(error).toMatchObject( + reason === "malformed" + ? { + code: "unsupported_target", + details: { operation: selection.operation, + path: fixture.sourcePath, failure_kind: "malformed", - path: expect.stringContaining(fixture.sourcePath), - } - : { + }, + } + : { + code: "artifact_operation_failed", + details: { operation: selection.operation, reason, detail: expect.stringContaining("../outside.js"), }, - }); + }, + ); } } @@ -167,7 +169,11 @@ cliTest( expect(missing.json).not.toHaveProperty("normalized_result"); const missingMcp = await call(location.operation, location.input); expect(missingMcp.structuredContent).toBeUndefined(); - expect(parseMcpToolError(missingMcp).error).toEqual(missing.json); + expectAdapterErrorParity( + parseMcpToolError(missingMcp).error, + missing.json, + location.operation, + ); const invalidBytes = Buffer.from([255, 254]); await writeFile(mapPath, invalidBytes); diff --git a/tests/boundary/binaryDiagnostics/pwntoolsLayoutProvider.test.ts b/tests/boundary/binaryDiagnostics/pwntoolsLayoutProvider.test.ts index 50174815c6..e38bddcd7e 100644 --- a/tests/boundary/binaryDiagnostics/pwntoolsLayoutProvider.test.ts +++ b/tests/boundary/binaryDiagnostics/pwntoolsLayoutProvider.test.ts @@ -462,7 +462,7 @@ it.runIf(!unsupportedHost)( request.reply_path, JSON.stringify({ ok: false, - reason: "format", + reason: "malformed", message: "Malformed original ELF table.", }), ); @@ -533,7 +533,7 @@ it .runIf(!unsupportedHost) .each([ "success", - "format", + "malformed", "unavailable", "unsupported", "output-limit", @@ -567,16 +567,17 @@ it } = binaryLayoutFixture(path); const encodedReplies: Partial> = { "invalid-utf8": Buffer.concat([ - Buffer.from('{"ok":false,"reason":"format","message":"'), + Buffer.from('{"ok":false,"reason":"malformed","message":"'), Buffer.from([0xff]), Buffer.from('"}'), ]), "literal-replacement": JSON.stringify({ ok: false, - reason: "format", + reason: "malformed", message: "valid �", }), - "bom-reply": '\uFEFF{"ok":false,"reason":"format","message":"valid"}', + "bom-reply": + '\uFEFF{"ok":false,"reason":"malformed","message":"valid"}', }; const encodedReply = encodedReplies[scenario]; if (encodedReply !== undefined) @@ -588,7 +589,7 @@ it ? "broken-json" : JSON.stringify( [ - "format", + "malformed", "unavailable", "unsupported", "output-limit", @@ -635,7 +636,7 @@ it ok: false, error: { _tag: - scenario === "format" || scenario === "literal-replacement" + scenario === "malformed" || scenario === "literal-replacement" ? "AnalysisTargetFailureError" : scenario === "unavailable" ? "ProviderSelectionError" diff --git a/tests/boundary/browser/historicalCaptureDecoder.test.ts b/tests/boundary/browser/historicalCaptureDecoder.test.ts index f7fbe06472..33edec762c 100644 --- a/tests/boundary/browser/historicalCaptureDecoder.test.ts +++ b/tests/boundary/browser/historicalCaptureDecoder.test.ts @@ -902,7 +902,7 @@ it.skipIf(process.platform === "win32" || process.getuid?.() === 0)( }, ); -it.each(["format", "process"])( +it.each(["malformed", "process"])( "preserves the structured %s failure when runtime cleanup fails", async (kind) => { const root = await createTestTempDirectory("rea-historical-cleanup-"); @@ -914,12 +914,12 @@ it.each(["format", "process"])( format: "har", identity: HAR_CAPTURE_PROVIDER_IDENTITY, command: async (_, runtimePath) => { - if (kind === "format") + if (kind === "malformed") await writeFile( join(runtimePath, "reply.json"), JSON.stringify({ ok: false, - reason: "format", + reason: "malformed", message: "Malformed retained record", pointer: "/metadata/capture-private", }), @@ -928,7 +928,7 @@ it.each(["format", "process"])( command: process.execPath, arguments: [ "-e", - kind === "format" + kind === "malformed" ? "process.exit(0)" : 'process.stderr.write("Specific provider fault"); process.exit(3)', ], @@ -959,7 +959,7 @@ it.each(["format", "process"])( ); if (result.ok) throw new Error("Cleanup failure required"); expect(result.error.cleanupPrimary?._tag).toBe( - kind === "format" ? "AnalysisInputError" : "ProviderAdapterError", + kind === "malformed" ? "AnalysisInputError" : "ProviderAdapterError", ); const projected = projectAnalysisError(result.error); expect(projected).toMatchObject({ @@ -967,7 +967,7 @@ it.each(["format", "process"])( details: { diagnostics: { primary_error: - kind === "format" + kind === "malformed" ? { category: "invalid_input", details: { diff --git a/tests/boundary/cli/browserInputDiagnostics.test.ts b/tests/boundary/cli/browserInputDiagnostics.test.ts index b26ea26169..d06e1c3f64 100644 --- a/tests/boundary/cli/browserInputDiagnostics.test.ts +++ b/tests/boundary/cli/browserInputDiagnostics.test.ts @@ -181,7 +181,7 @@ describe("browser and Inspector CLI input diagnostics", () => { message: expect.stringMatching(/input.*invalid/iu), retryable: false, remediation: { - action: expect.stringContaining(input.operation), + action: expect.stringContaining(`rea ${input.command}`), }, recovery: { kind: "inspect_input_contract", @@ -198,9 +198,10 @@ describe("browser and Inspector CLI input diagnostics", () => { ]), }, }); - expect(result.json).toMatchObject({ - remediation: { action: expect.stringContaining("tools/list") }, - }); + const action = (result.json as { remediation: { action: string } }) + .remediation.action; + expect(action).not.toContain(input.operation); + expect(action).not.toContain("tools/list"); expect(result.stdout).not.toContain(malformedEndpoint); expect(result.stderr).not.toContain(malformedEndpoint); }, diff --git a/tests/boundary/cli/projectCliAnalysisResult.test.ts b/tests/boundary/cli/projectCliAnalysisResult.test.ts index 41a7134bb6..e71a770acd 100644 --- a/tests/boundary/cli/projectCliAnalysisResult.test.ts +++ b/tests/boundary/cli/projectCliAnalysisResult.test.ts @@ -1,6 +1,9 @@ import { expect, it } from "vitest"; -import { AnalysisInputError } from "../../../src/domain/analysisErrorCore.js"; +import { + AnalysisInputError, + AnalysisTargetFailureError, +} from "../../../src/domain/analysisErrorCore.js"; import { analysisErrorWithCleanupFailure } from "../../../src/domain/analysisErrorCleanup.js"; import { projectAnalysisError } from "../../../src/domain/analysisErrorProjection.js"; import { freezeJsonSnapshot } from "../../../src/domain/immutableJson.js"; @@ -8,6 +11,10 @@ import { ProviderCleanupError } from "../../../src/domain/providerCleanupError.j import { createCli } from "../../../src/cli.js"; import { cliCommand, cliCommands } from "../../../src/cli/commandRegistry.js"; import { ArtifactOperationError } from "../../../src/domain/artifactOperationError.js"; +import { + MCP_TARGET_FAILURE_SPELLING, + renderTargetFailureRecovery, +} from "../../../src/domain/targetFailure.js"; import { projectCliCommandOutput, projectCliInputFields, @@ -123,6 +130,25 @@ it("passes through successful data, unbound operations and unknown error values" expect(projectCliInputFields(unknown, binding)).toEqual(unknown); }); +it("spells an input refusal with the CLI command and drops the MCP catalog clause", () => { + const cli = createCli(); + const entries = cliCommands(cli); + const entry = cliCommand(cli, "inspect-pe-resources"); + if (entry === undefined) throw new Error("Expected inspect-pe-resources"); + const projected = projectAnalysisError( + new AnalysisInputError("inspect_pe_resources", undefined, [ + { path: ["path"], reason: "invalid_value" }, + ]), + ); + const cliProjected = projectCliCommandOutput(projected, { + operations: entry.operations, + commands: entries, + }) as { remediation: { action: string } }; + expect(cliProjected.remediation.action).toContain("rea inspect-pe-resources"); + expect(cliProjected.remediation.action).not.toContain("inspect_pe_resources"); + expect(cliProjected.remediation.action).not.toContain("tools/list"); +}); + it("renders related_cli_flags and related_cli_commands from the CLI command registry across command shapes", () => { const cli = createCli(); const entries = cliCommands(cli); @@ -273,3 +299,206 @@ it("names a flattened member flag or the JSON flag for its containing group", () }), ).toEqual(data); }); + +it("names a target failure's alternative operations and providers in each adapter's spelling", () => { + const cli = createCli(); + const entries = cliCommands(cli); + const entry = cliCommand(cli, "inspect-artifact"); + if (entry === undefined) throw new Error("Expected inspect-artifact"); + const projected = projectAnalysisError( + new AnalysisTargetFailureError( + "inspect_artifact", + "/selected/app", + { + kind: "unsupported", + format: "directory", + detail: "No container format claims the directory", + undecodedContent: false, + }, + { + related: { + operations: ["inspect_desktop_application"], + providers: ["ghidra"], + }, + }, + ), + ); + const facts = { + operation: "inspect_artifact", + kind: "unsupported" as const, + format: "directory", + alternatives: { + operations: ["inspect_desktop_application"], + providers: ["ghidra"], + }, + }; + // MCP, and Evidence, name the tool and the open_binary argument. + expect(projected).toMatchObject({ + remediation: { + action: renderTargetFailureRecovery(facts, MCP_TARGET_FAILURE_SPELLING), + }, + details: { + related_operations: ["inspect_desktop_application"], + related_providers: ["ghidra"], + }, + }); + expect(projected.remediation.action).toContain("inspect_artifact"); + expect(projected.remediation.action).toContain("inspect_desktop_application"); + expect(projected.remediation.action).toContain( + 'open_binary with provider_id "ghidra"', + ); + // The CLI renders the same table entry with its commands and option. + const cliProjected = projectCliCommandOutput(projected, { + operations: entry.operations, + commands: entries, + }) as { remediation: { action: string } }; + expect(cliProjected).toMatchObject({ + remediation: { + action: renderTargetFailureRecovery(facts, { + operation: (op) => + op === "inspect_artifact" + ? "rea inspect-artifact" + : "rea inspect-desktop-application", + provider: (providerId) => `--provider ${providerId}`, + }), + }, + }); + expect(cliProjected.remediation.action).toContain("rea inspect-artifact"); + expect(cliProjected.remediation.action).toContain( + "rea inspect-desktop-application", + ); + expect(cliProjected.remediation.action).toContain("--provider ghidra"); +}); + +it("rewrites target recovery when cleanup drops the retry hint", () => { + const cli = createCli(); + const entries = cliCommands(cli); + const entry = cliCommand(cli, "inspect-artifact"); + if (entry === undefined) throw new Error("Expected inspect-artifact"); + const projected = projectAnalysisError( + new AnalysisTargetFailureError( + "inspect_artifact", + "/selected/app", + { + kind: "malformed", + format: "zip", + detail: "ZIP archive is malformed: bad crc", + }, + { cleanup: { reason: "close failed", resources: ["/selected/app"] } }, + ), + ); + expect(projected).toMatchObject({ + code: "cleanup_incomplete", + details: { failure_kind: "malformed", format: "zip" }, + }); + expect(projected.retry).toBeUndefined(); + expect(projected.remediation.action).toContain("inspect_artifact"); + const cliProjected = projectCliCommandOutput(projected, { + operations: entry.operations, + commands: entries, + }) as { remediation: { action: string } }; + expect(cliProjected.remediation.action).toContain("rea inspect-artifact"); + expect(cliProjected.remediation.action).not.toContain("inspect_artifact"); +}); + +it("omits MCP-only alternative operations from CLI target failure recovery", () => { + const cli = createCli(); + const entries = cliCommands(cli); + const entry = cliCommand(cli, "inspect-analysis-view"); + if (entry === undefined) throw new Error("Expected inspect-analysis-view"); + const projected = projectAnalysisError( + new AnalysisTargetFailureError( + "inspect_analysis_view", + "/selected/evidence.json", + { + kind: "unsupported", + format: "evidence", + detail: + "inspect_recorded_crash Evidence does not expose analysis views", + undecodedContent: false, + }, + { + related: { + operations: ["get_evidence_bundle", "export_evidence_bundle"], + }, + }, + ), + ); + const cliProjected = projectCliCommandOutput(projected, { + operations: entry.operations, + commands: entries, + }) as { remediation: { action: string } }; + expect(cliProjected.remediation.action).toBe( + renderTargetFailureRecovery( + { + operation: "inspect_analysis_view", + kind: "unsupported", + format: "evidence", + }, + { + operation: () => "rea inspect-analysis-view", + provider: (providerId) => `--provider ${providerId}`, + }, + ), + ); + expect(cliProjected.remediation.action).toContain( + "rea inspect-analysis-view", + ); + expect(cliProjected.remediation.action).not.toContain("get_evidence_bundle"); + expect(cliProjected.remediation.action).not.toContain( + "export_evidence_bundle", + ); +}); + +it("rewrites conflict recovery input names to CLI flags even after renaming details.inputs", () => { + const cli = createCli(); + const entries = cliCommands(cli); + const entry = cliCommand(cli, "inspect-il2cpp-metadata"); + if (entry === undefined) throw new Error("Expected inspect-il2cpp-metadata"); + const projected = projectAnalysisError( + new AnalysisTargetFailureError( + "inspect_il2cpp_metadata", + "/selected/global-metadata.dat", + { + kind: "conflict", + format: "il2cpp-metadata", + detail: "code-registration-not-found: no registration matched", + inputs: [ + { field: "path", path: "/selected/global-metadata.dat" }, + { field: "binary_path", path: "/selected/GameAssembly.dylib" }, + ], + }, + ), + ); + expect(projected.remediation.action).toContain("(path, binary_path)"); + + // Contract commands run projectCliInputFields before projectCliCommandOutput. + const fieldProjected = projectCliInputFields(projected, { + operation: "inspect_il2cpp_metadata", + fields: { binary_path: "binary" }, + flags: { binary_path: "--binary" }, + operations: entry.operations, + }); + const cliProjected = projectCliCommandOutput(fieldProjected, { + operations: entry.operations, + commands: entries, + }); + expect(cliProjected).toMatchObject({ + details: { + inputs: [ + { field: "path", path: "/selected/global-metadata.dat" }, + { field: "binary", path: "/selected/GameAssembly.dylib" }, + ], + }, + }); + expect(cliProjected.remediation.action).toContain("(path, --binary)"); + expect(cliProjected.remediation.action).not.toContain("binary_path"); + + // Direct command-output projection without prior field renaming also maps flags. + const directProjected = projectCliCommandOutput(projected, { + operations: entry.operations, + commands: entries, + }); + expect(directProjected.remediation.action).toContain("(path, --binary)"); + expect(directProjected.remediation.action).not.toContain("binary_path"); +}); diff --git a/tests/boundary/evm/evmCleanupRetry.test.ts b/tests/boundary/evm/evmCleanupRetry.test.ts index a05e6ebbd1..6d666b242a 100644 --- a/tests/boundary/evm/evmCleanupRetry.test.ts +++ b/tests/boundary/evm/evmCleanupRetry.test.ts @@ -722,7 +722,7 @@ it.each([ const bytes = Buffer.from("60006000f3", "hex"); const reply = scenario === "refusal" - ? { ok: false, reason: "format", message: "invalid carrier" } + ? { ok: false, reason: "malformed", message: "invalid carrier" } : { ok: true, version: diff --git a/tests/boundary/evm/evmoleInterfaceProvider.test.ts b/tests/boundary/evm/evmoleInterfaceProvider.test.ts index e79f395a8a..0f4f3f50ff 100644 --- a/tests/boundary/evm/evmoleInterfaceProvider.test.ts +++ b/tests/boundary/evm/evmoleInterfaceProvider.test.ts @@ -391,7 +391,7 @@ it .runIf(!unsupportedHost) .each([ "success", - "format", + "malformed", "unsupported", "output-limit", "wrong-version", @@ -426,16 +426,17 @@ it const bytes = Buffer.from(hex, "hex"); const encodedReplies: Partial> = { "invalid-utf8": Buffer.concat([ - Buffer.from('{"ok":false,"reason":"format","message":"'), + Buffer.from('{"ok":false,"reason":"malformed","message":"'), Buffer.from([0xff]), Buffer.from('"}'), ]), "literal-replacement": JSON.stringify({ ok: false, - reason: "format", + reason: "malformed", message: "valid �", }), - "bom-reply": '\uFEFF{"ok":false,"reason":"format","message":"valid"}', + "bom-reply": + '\uFEFF{"ok":false,"reason":"malformed","message":"valid"}', }; const encodedReply = encodedReplies[scenario]; if (encodedReply !== undefined) @@ -446,7 +447,9 @@ it scenario === "broken-reply" ? "broken" : JSON.stringify( - ["format", "unsupported", "output-limit"].includes(scenario) + ["malformed", "unsupported", "output-limit"].includes( + scenario, + ) ? { ok: false, reason: scenario, @@ -510,7 +513,7 @@ it ok: false, error: { _tag: - scenario === "format" || scenario === "literal-replacement" + scenario === "malformed" || scenario === "literal-replacement" ? "AnalysisTargetFailureError" : scenario === "unsupported" ? "AnalysisTargetFailureError" @@ -798,7 +801,7 @@ it.runIf(!unsupportedHost)( request.reply_path, JSON.stringify({ ok: false, - reason: "format", + reason: "malformed", message: "Odd selected hex.", }), ); diff --git a/tests/boundary/javascriptSemanticTraceEvidence.test.ts b/tests/boundary/javascriptSemanticTraceEvidence.test.ts index 5385608621..a2e7c28a5f 100644 --- a/tests/boundary/javascriptSemanticTraceEvidence.test.ts +++ b/tests/boundary/javascriptSemanticTraceEvidence.test.ts @@ -7,7 +7,10 @@ import { afterAll, expect, it } from "vitest"; import { Ajv2020 } from "ajv/dist/2020.js"; import { createApplicationMcpHarness } from "../fixtures/applicationMcpHarness.js"; -import { parseMcpToolError } from "../fixtures/mcpToolError.js"; +import { + expectAdapterErrorParity, + parseMcpToolError, +} from "../fixtures/mcpToolError.js"; import { createTestTempDirectory } from "../fixtures/temporaryDirectory.js"; import { closeCliResources, createCli } from "../../src/cli.js"; import { createEvidence, parseEvidence } from "../../src/domain/evidence.js"; @@ -116,7 +119,7 @@ it("reports invalid nested semantic graph Evidence as caller input through CLI a arguments: arguments_, }); const { error: mcpError } = parseMcpToolError(mcpTrace); - expect(mcpError).toEqual(cliError); + expectAdapterErrorParity(mcpError, cliError, "trace_javascript_semantics"); } finally { await harness.close(); } diff --git a/tests/boundary/mcp/analysisViewMcp.test.ts b/tests/boundary/mcp/analysisViewMcp.test.ts index ac6ba6e499..68841a46a9 100644 --- a/tests/boundary/mcp/analysisViewMcp.test.ts +++ b/tests/boundary/mcp/analysisViewMcp.test.ts @@ -1826,6 +1826,7 @@ it("extracts an environment state identically from retained, portable and file M const hiddenError = parseMcpToolError(refused).error; expect(hiddenError).toMatchObject({ code: "unsupported_target", + retry: "none", details: { failure_kind: "unsupported", format: "evidence", @@ -2089,6 +2090,7 @@ it("projects an environment manifest identically from retained, portable and fil const hiddenError = parseMcpToolError(refused).error; expect(hiddenError).toMatchObject({ code: "unsupported_target", + retry: "none", details: { failure_kind: "unsupported", format: "evidence", diff --git a/tests/boundary/mcp/browserScenarioInputDiagnosticsMcp.test.ts b/tests/boundary/mcp/browserScenarioInputDiagnosticsMcp.test.ts index ab6f5aadaf..4e089203d1 100644 --- a/tests/boundary/mcp/browserScenarioInputDiagnosticsMcp.test.ts +++ b/tests/boundary/mcp/browserScenarioInputDiagnosticsMcp.test.ts @@ -6,7 +6,10 @@ import { afterAll, expect } from "vitest"; import { z } from "zod"; import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; -import { parseMcpToolError } from "../../fixtures/mcpToolError.js"; +import { + expectAdapterErrorParity, + parseMcpToolError, +} from "../../fixtures/mcpToolError.js"; import { cliTest } from "../../support/cli/cliFixture.js"; import { createMcpSchemaValidation } from "../../fixtures/mcpSchemaValidation.js"; @@ -153,7 +156,7 @@ cliTest( category: "invalid_input", retryable: false, remediation: { - action: expect.stringContaining("capture_browser_scenario"), + action: expect.stringContaining("rea capture-browser-scenario"), }, recovery: { kind: "inspect_input_contract", @@ -171,8 +174,17 @@ cliTest( }); expect(mcpResult.structuredContent).toBeUndefined(); const mcpError = parseMcpToolError(mcpResult).error; + const cliAction = z + .object({ remediation: z.object({ action: z.string() }) }) + .parse(cliDiagnostic).remediation.action; + expect(cliAction).not.toContain("capture_browser_scenario"); + expect(cliAction).not.toContain("tools/list"); if (scenario.canonicalRefinement) - expect(mcpError).toEqual(cliDiagnostic); + expectAdapterErrorParity( + mcpError, + cliDiagnostic, + "capture_browser_scenario", + ); else { // The SDK validates the canonical schema before invoking the handler. expect(mcpError).toMatchObject({ diff --git a/tests/boundary/mcp/managedNativeVerificationAdapters.test.ts b/tests/boundary/mcp/managedNativeVerificationAdapters.test.ts index 43bfa59376..a8185ce786 100644 --- a/tests/boundary/mcp/managedNativeVerificationAdapters.test.ts +++ b/tests/boundary/mcp/managedNativeVerificationAdapters.test.ts @@ -14,7 +14,10 @@ import { managedApplicationGraphReferenceInputSchema } from "../../../src/domain import { managedNativeVerificationResultSchema } from "../../../src/domain/managed/managedNativeVerificationSchemas.js"; import { buildManagedPeFixture } from "../../../src/dotnet/ManagedPe.fixture.js"; import { fileLocalToolsMcp } from "../../fixtures/localToolsMcp.js"; -import { parseMcpToolError } from "../../fixtures/mcpToolError.js"; +import { + expectAdapterErrorParity, + parseMcpToolError, +} from "../../fixtures/mcpToolError.js"; import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; import { cliTest } from "../../support/cli/cliFixture.js"; @@ -126,7 +129,11 @@ cliTest( ], }); expect(wrongCommand.exitCode, wrongCommand.stderr).toBe(1); - expect(wrongCommand.json).toMatchObject(wrongError); + expectAdapterErrorParity( + wrongError, + wrongCommand.json, + "project_managed_application_graph", + ); const control = await fileMcp.client.callTool({ name: "project_managed_application_graph", diff --git a/tests/boundary/providers/native/nativeDmgArtifactReader.test.ts b/tests/boundary/providers/native/nativeDmgArtifactReader.test.ts index a94ddeabc2..8f82c7fe6e 100644 --- a/tests/boundary/providers/native/nativeDmgArtifactReader.test.ts +++ b/tests/boundary/providers/native/nativeDmgArtifactReader.test.ts @@ -28,7 +28,10 @@ import { type NativeDmgHost, } from "../../../../src/artifacts/NativeDmgArtifactReader.js"; import { scanCanonicalArtifactInventoryInScope } from "../../../../src/artifacts/inventory/scanCanonical.js"; -import { DirectoryArtifactReader } from "../../../../src/resources/index.js"; +import { + DirectoryArtifactReader, + translateArtifactFailure, +} from "../../../../src/resources/index.js"; const createAttachedReader = async ( path: string, @@ -1336,9 +1339,19 @@ describe("native DMG permanent verification refusals", () => { }, ); onTestFinished(() => reader.close()); - await expect(entryPaths(reader)).rejects.toMatchObject({ + const failure = await entryPaths(reader).catch((cause: unknown) => cause); + expect(failure).toMatchObject({ reason, integrityCheck: reason === "integrity" ? "image-checksum" : undefined, + parseFailure: + reason === "unsupported" + ? { + kind: "unsupported", + format: "dmg", + detail: expect.stringContaining(diagnostic), + undecodedContent: false, + } + : undefined, cause: { command: "/usr/bin/hdiutil", exitCode: 1, stdout, stderr }, message: expect.stringContaining( reason === "unavailable" @@ -1346,6 +1359,30 @@ describe("native DMG permanent verification refusals", () => { : diagnostic, ), }); + const translated = translateArtifactFailure( + "inventory_artifact", + path, + failure, + ); + expect(translated).toMatchObject( + reason === "unsupported" + ? { + _tag: "AnalysisTargetFailureError", + operation: "inventory_artifact", + path, + failure: { + kind: "unsupported", + format: "dmg", + undecodedContent: false, + detail: expect.stringContaining(diagnostic), + }, + } + : { + _tag: "ArtifactOperationError", + operation: "inventory_artifact", + reason, + }, + ); expect(run.mock.calls).toHaveLength(1); expect(reader.provenance()).toMatchObject([ { arguments: ["verify", path], exit_code: 1, effects: ["read"] }, diff --git a/tests/boundary/uefi/lzmaWorker.test.ts b/tests/boundary/uefi/lzmaWorker.test.ts index f8a3472b8c..2c90495dfc 100644 --- a/tests/boundary/uefi/lzmaWorker.test.ts +++ b/tests/boundary/uefi/lzmaWorker.test.ts @@ -81,21 +81,21 @@ it("returns typed limit and framing refusals through stdio without losing the ne "short header", valid.subarray(0, 9), 1024, - "format", + "malformed", "Incomplete LZMA stream header", ], [ "short coded body", valid.subarray(0, -1), 1024, - "format", + "malformed", "Compressed stream ends before the decoder can finish", ], [ "initial range coder byte", wrongLeadIn, 1024, - "format", + "malformed", "range coder byte must be zero", ], [ diff --git a/tests/fixtures/mcpToolError.ts b/tests/fixtures/mcpToolError.ts index 19e7db6af0..8de58566b9 100644 --- a/tests/fixtures/mcpToolError.ts +++ b/tests/fixtures/mcpToolError.ts @@ -14,3 +14,27 @@ export function parseMcpToolError(result: CallToolResult) { .strict() .parse(JSON.parse(text.text)); } + +/** + * Expect MCP and CLI to report the same failure facts. Only the recovery + * differs: each adapter names an operation in its own spelling, so the CLI + * recovery never carries the MCP name and uses `rea ` wherever MCP + * names the operation. + */ +export function expectAdapterErrorParity( + mcpError: { readonly remediation: { readonly action: string } }, + cliJson: unknown, + operation: string, +) { + const { remediation: mcpRecovery, ...mcpFacts } = mcpError; + const { remediation: cliRecovery, ...cliFacts } = z + .object({ remediation: z.object({ action: z.string() }).loose() }) + .loose() + .parse(cliJson); + expect(mcpFacts).toEqual(cliFacts); + expect(cliRecovery.action).not.toContain(operation); + if (mcpRecovery.action.includes(operation)) + expect(cliRecovery.action).toContain( + `rea ${operation.replaceAll("_", "-")}`, + ); +}