Files
frame/tests/test_check_plugin_policy.py
Lainandlain e71842aa8a feat(poc-a): gate-a dynamic elf proof of concept (#13)
## Summary

PoC-A proved that dynamically loaded ELF plugins are workable on
ESP32-S3: plugins ship as signed MPB packages, are parsed by a strict
single-type parser shared between host and target, and execute from
PSRAM+IRAM within a measured admission budget. A 1000-cycle load/unload
soak passed 18/18 trend gates with stable heaps, the capacity ladder
settled at 8 coexisting plugin instances with a 3356B per-instance
budget, and the fail-closed corpus executed zero attacker-controlled
bytes across 14 rejection classes. Scheduler semantics (strand FIFO
ordering, completion-cancel CAS, quiesce-as-noop ABI) were validated on
both host (TSan suite) and target. **Gate-A verdict: PASS** — ADR-0002
moves to **Accepted** with the capacity value 8 and global-sum admission
rule as PoC-derived proposals.

## Changes by area

Grouped from `git log main..HEAD --oneline` (18 commits):

- **Vendored loader + patches**: `4bb53f2` vendor elf_loader 1.3.3 +
harness scaffold; `2f67b4f` plugin_iram loader patch with budget
consistency (p1-p5 patch series in `PATCHES.md`).
- **MPB toolchain**: `4793cc2` deterministic MPB manifest builder with
test signing; `408df44` strict single-type MPB parser shared
host/target; `796f9d2` host MPB corpus + policy CI lane.
- **Plugin pipeline + probes**: `21d2842` plugin pipeline and first
PSRAM execution on target; `cab9664` relocation/import allowlist matrix
with probes; `c5d6c6c` C++ feature rejection matrix.
- **Harness commands**: `e0e7159` generation coexistence with measured
admission budget; `2a37556` thousand-cycle lifecycle soak with heap
trend gate; `093a72b` on-target scheduler semantics validation (+
`eea3876` clang-format-18 sweep); `a302151` capacity ladder with signed
budget; `f34dc72` fail-closed corpus with execution sentinel.
- **Host prototypes**: `6198bca` strand FIFO prototype with TSan suite;
`1c3ad59` completion-cancel CAS and cleanup semantics.
- **Evidence + ADR/docs**: `887d0f7` Gate-A manifest and report;
`1c29e8a` ADR-0002 outcome + frozen PoC values.

## QA evidence

- `poc/evidence/poc-a-20260901/manifest.json` — 67-artifact hash index,
every sha256 recomputed at assembly.
- `poc/evidence/poc-a-20260901/GATE-A-REPORT.md` — full nine-item
development-plan §4 mapping; TEST-003 10/10 clauses.
- 14 verbatim per-task transcripts (`task-1` … `task-15-*.log`) + fresh
build artifacts (`build/frame_poc_a.map`, size components).
- Frozen in-repo references: `ALLOWLIST.md`, `REJECT-MATRIX.md`,
`ADMISSION-BUDGET.md`, `soak_samples_1000.csv`, fc corpus (33 committed
`.mpb` containers).
- F1-F4 final-wave verdicts: **APPROVE**.
- Key numbers: soak **18/18** trend gates over 1000 cycles; capacity
**8/8** instances, **3356B** per-instance; fc corpus **14 rejection
classes, zero attacker bytes executed**; **4 upstream loader defects
found and patched** (p1-p5).

## Requirement IDs (GOV-006)

ADR-0002; TEST-002, TEST-003; PLUG-001, PLUG-004, PLUG-008, PLUG-009;
MEM-001, MEM-003, MEM-007, MEM-008; LIFE-001, LIFE-002, LIFE-005,
LIFE-007; SEC-002, SEC-003, SEC-004, SEC-005; GH-003; GOV-004, GOV-005.

## Risks / known limitations

From `GATE-A-REPORT.md` §(f) plus the trade-off table:

1. **Capacity descent path 7-5 unexercised** — rung 8 passed first
attempt; rungs 7/6/5 and retry-once logic never ran on hardware
(untested against real OOM).
2. **No Wi-Fi in the harness (MEM-001 caveat)** — all PSRAM/IRAM budget
numbers are radio-off harness-class; product admission budgets must be
re-measured with the network stack active.
3. **On-target scheduler vectors are a subset of the host suite**
(256-node pool / 2e4 storm posts vs host 31000 / 1e5); consistency
declaration covers only the vectors actually run.
4. **Quiesce is a no-op by ABI semantics** — plugin ABI 1.2 has no
quiesce slot; NULL entry is defined as trivial success; real quiesce
coordination is later-gate work.
5. **MEMPROT=n trade-off** — `CONFIG_ESP_SYSTEM_MEMPROT=n` is required
for the IDF exec heap (`MALLOC_CAP_EXEC`) that `.plugin_iram` needs;
software-only PMP config, no eFuse burned (documented in `PATCHES.md`
p5); production must re-decide security vs plugin IRAM.
6. **Owner sign-off PENDING** — Gate-A PASS is the PoC team's verdict;
formal acceptance of ADR-0002 awaits the owner.

## Not in scope

- Product components (GOV-004) — this PR is PoC evidence only; no
product code paths change.
- **Merge is the owner's call** — do not merge without owner sign-off on
ADR-0002.

---------

Co-authored-by: ania-lain <[email protected]>
2026-09-07 20:02:18 +08:00

297 lines
10 KiB
Python

"""Tests for the host plugin-policy gate (GH-003, appendix C 11.3 subset).
The policy checker is exercised on synthetic ELF32 LE Xtensa images built by
this module, so the suite runs host-only (no xtensa toolchain needed). The
stem drift guard additionally pins the forbidden-section list to a single
source: the list in ``check_plugin_policy.py`` must equal both gate 4 of
``check_plugin_elf.cmake`` and the p4 hunk recorded in ``PATCHES.md``.
"""
from __future__ import annotations
import re
import struct
from collections.abc import Sequence
from pathlib import Path
import pytest
from frame_tools.check_plugin_policy import (
DEFAULT_ENTRY,
FORBIDDEN_SECTION_STEMS,
check_policy,
section_stem,
)
from frame_tools.check_plugin_policy import (
main as cli_main,
)
REPO = Path(__file__).resolve().parents[1]
CMAKE_GATE = REPO / "poc/apps/poc_a/plugins/check_plugin_elf.cmake"
PATCHES_MD = REPO / "poc/apps/poc_a/components/elf_loader/PATCHES.md"
STT_FUNC = 2
STT_OBJECT = 1
STB_GLOBAL = 1
SHT_PROGBITS = 1
EM_XTENSA = 94
def build_elf(
*,
extra_sections: Sequence[str] = (),
undefined: Sequence[str] = (),
defined_globals: Sequence[tuple[str, int]] | None = None,
rela: Sequence[tuple[int, int]] = ((5, 0),),
rel: Sequence[tuple[int, int]] = (),
ei_class: int = 1,
ei_data: int = 1,
machine: int = EM_XTENSA,
e_type: int = 3,
bad_rela_entsize: bool = False,
) -> bytes:
"""Synthesize a minimal plugin-shaped ELF32 LE image.
``rela``/``rel`` entries are ``(reloc_type, symbol_index)`` pairs packed
into ``.rela.dyn``/``.rel.dyn``; ``defined_globals`` defaults to exactly
the query entry, mirroring the stripped positive-pipeline artifacts.
"""
if defined_globals is None:
defined_globals = [(DEFAULT_ENTRY, STT_FUNC)]
section_order = [
".text",
*extra_sections,
".rela.dyn",
".rel.dyn",
".shstrtab",
".strtab",
".symtab",
]
sh_names: dict[str, int] = {}
shstrtab = b"\x00"
for name in section_order:
sh_names[name] = len(shstrtab)
shstrtab += name.encode() + b"\x00"
header_index = {name: index + 1 for index, name in enumerate(section_order)}
sym_names: dict[str, int] = {}
strtab = b"\x00"
for name in [n for n, _ in defined_globals] + list(undefined):
if name not in sym_names:
sym_names[name] = len(strtab)
strtab += name.encode() + b"\x00"
blobs: list[tuple[str, int, bytes]] = []
cursor = 52
for name, blob in (
(".text", b"\x00" * 16),
(".shstrtab", shstrtab),
(".strtab", strtab),
):
blobs.append((name, cursor, blob))
cursor += len(blob)
symbols = [(0, 0, 0, 0, 0, 0)]
for name, sym_type in defined_globals:
symbols.append((sym_names[name], 0x100, 0, (STB_GLOBAL << 4) | sym_type, 0, 1))
for name in undefined:
symbols.append((sym_names[name], 0, 0, STB_GLOBAL << 4, 0, 0))
symtab = b"".join(struct.pack("<IIIBBH", *sym) for sym in symbols)
blobs.append((".symtab", cursor, symtab))
cursor += len(symtab)
rela_bytes = b"".join(
struct.pack("<IIi", 0x198, (reloc_type << 8) | sym_index, 0)
for reloc_type, sym_index in rela
)
blobs.append((".rela.dyn", cursor, rela_bytes))
cursor += len(rela_bytes)
rel_bytes = b"".join(
struct.pack("<II", 0x1A0, (reloc_type << 8) | sym_index) for reloc_type, sym_index in rel
)
blobs.append((".rel.dyn", cursor, rel_bytes))
cursor += len(rel_bytes)
placed = {name: (offset, len(blob)) for name, offset, blob in blobs}
def shdr(name: str, sh_type: int, link: int = 0, entsize: int = 0) -> bytes:
offset, size = placed[name]
return struct.pack(
"<10I", sh_names[name], sh_type, 0, 0x1000, offset, size, link, 0, 4, entsize
)
shdrs = b"\x00" * 40
shdrs += shdr(".text", SHT_PROGBITS)
for name in extra_sections:
placed[name] = (placed[".text"][0], 0)
shdrs += shdr(name, SHT_PROGBITS)
shdrs += shdr(".rela.dyn", 4, entsize=99 if bad_rela_entsize else 12)
shdrs += shdr(".rel.dyn", 9, entsize=8)
shdrs += shdr(".shstrtab", 3)
shdrs += shdr(".strtab", 3)
shdrs += shdr(".symtab", 2, link=header_index[".strtab"], entsize=16)
shnum = len(section_order) + 1
ident = b"\x7fELF" + bytes([ei_class, ei_data, 1, 0]) + b"\x00" * 8
ehdr = ident + struct.pack(
"<HHIIIIIHHHHHH",
e_type,
machine,
1,
0x100,
0,
cursor,
0,
52,
0,
0,
40,
shnum,
header_index[".shstrtab"],
)
return ehdr + b"".join(blob for _, _, blob in blobs) + shdrs
def gate4_stems() -> list[str]:
match = re.search(
r"set\(forbidden_stems\s+(.*?)\)", CMAKE_GATE.read_text(encoding="utf-8"), re.DOTALL
)
assert match, "gate 4 stem list not found in check_plugin_elf.cmake"
return match.group(1).split()
def p4_stems() -> list[str]:
text = PATCHES_MD.read_text(encoding="utf-8")
match = re.search(r"static const char \*const forbidden\[\] = \{(.*?)\};", text, re.DOTALL)
assert match, "p4 forbidden[] list not found in PATCHES.md"
return [name.lstrip(".") for name in re.findall(r'"([^"]+)"', match.group(1))]
def test_forbidden_section_stems_have_a_single_source() -> None:
"""Drift guard: checker list == cmake gate 4 == loader patch p4."""
assert gate4_stems() == list(FORBIDDEN_SECTION_STEMS)
assert p4_stems() == list(FORBIDDEN_SECTION_STEMS)
@pytest.mark.parametrize(
("name", "stem"),
[
(".text", "text"),
(".ctors", "ctors"),
(".init_array.00001", "init_array"),
(".rela.init_array.00001", "init_array"),
(".rel.text", "text"),
(".gcc_except_table", "gcc_except_table"),
(".data.rel.ro", "data"),
],
)
def test_section_stem_mirrors_gate4_normalization(name: str, stem: str) -> None:
assert section_stem(name) == stem
def test_minimal_positive_plugin_passes() -> None:
elf = build_elf(undefined=("poca_host_add",), rela=((5, 0), (3, 1), (4, 1), (2, 0), (0, 0)))
assert check_policy(elf, allowed_imports=frozenset({"poca_host_add"})) == []
def test_undeclared_import_is_rejected() -> None:
elf = build_elf(undefined=("sprintf",))
violations = check_policy(elf, allowed_imports=frozenset({"poca_host_add"}))
assert any("import: undeclared undefined symbol 'sprintf'" in v for v in violations)
@pytest.mark.parametrize(
"allocator", ["malloc", "free", "calloc", "realloc", "_Znam", "_ZdlPv", "_ZdaPv"]
)
def test_allocator_imports_are_rejected_even_when_declared(allocator: str) -> None:
elf = build_elf(undefined=(allocator,))
violations = check_policy(elf, allowed_imports=frozenset({allocator}))
assert any("allocator: direct allocation import" in v for v in violations)
def test_extra_export_is_rejected() -> None:
elf = build_elf(defined_globals=[(DEFAULT_ENTRY, STT_FUNC), ("sneaky_export", STT_FUNC)])
violations = check_policy(elf)
assert any(v.startswith("export:") and "sneaky_export" in v for v in violations)
def test_missing_entry_is_rejected() -> None:
elf = build_elf(defined_globals=[("not_the_entry", STT_FUNC)])
violations = check_policy(elf)
assert any(v.startswith("export:") for v in violations)
def test_entry_must_be_a_function_symbol() -> None:
elf = build_elf(defined_globals=[(DEFAULT_ENTRY, STT_OBJECT)])
violations = check_policy(elf)
assert any("must be a FUNC symbol" in v for v in violations)
@pytest.mark.parametrize(
("reloc", "needle"), [(1, "R_XTENSA_32"), (20, "R_XTENSA_SLOT0_OP"), (11, "ASM_EXPAND")]
)
def test_out_of_allowlist_relocations_are_named_and_rejected(reloc: int, needle: str) -> None:
elf = build_elf(rela=((5, 0), (reloc, 0)))
violations = check_policy(elf)
assert any("reloc: forbidden relocation type" in v and needle in v for v in violations)
def test_tls_relocations_without_any_tls_section_are_rejected() -> None:
"""neg_tls_nosect pattern: sections renamed away, TLS reloc types remain."""
elf = build_elf(rela=((5, 0), (51, 0), (50, 0)))
violations = check_policy(elf)
assert any("R_XTENSA_TLSDESC_FN" in v for v in violations)
assert any("R_XTENSA_TLSDESC_ARG" in v for v in violations)
@pytest.mark.parametrize(
"section", [".ctors", ".init_array.00001", ".rela.tdata", ".eh_frame", ".dtors"]
)
def test_forbidden_cpp_feature_sections_are_rejected(section: str) -> None:
elf = build_elf(extra_sections=(section,))
violations = check_policy(elf)
assert any(f"forbidden C++ feature section {section!r}" in v for v in violations)
def test_sht_rel_sections_are_parsed_like_rela() -> None:
elf = build_elf(rela=(), rel=((5, 0), (1, 0)))
violations = check_policy(elf)
assert any("R_XTENSA_32" in v for v in violations)
@pytest.mark.parametrize(
"kwargs",
[
{"ei_class": 2},
{"ei_data": 2},
{"machine": 40},
{"e_type": 2},
{"bad_rela_entsize": True},
],
)
def test_shape_failures_fail_closed(kwargs: dict[str, int | bool]) -> None:
elf = build_elf(**kwargs) # type: ignore[arg-type]
assert check_policy(elf)
def test_cli_accepts_a_policy_clean_elf(tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None:
elf_path = tmp_path / "plugin.elf"
elf_path.write_bytes(build_elf(undefined=("poca_host_add",)))
allow = tmp_path / "imports.txt"
allow.write_text("# declared imports\npoca_host_add\n")
assert cli_main([f"--allow-imports-file={allow}", str(elf_path)]) == 0
assert "policy OK" in capsys.readouterr().out
def test_cli_rejects_a_violating_elf_and_names_the_reasons(
tmp_path: Path, capsys: pytest.CaptureFixture[str]
) -> None:
elf_path = tmp_path / "evil.elf"
elf_path.write_bytes(
build_elf(
extra_sections=(".ctors",),
undefined=("malloc",),
defined_globals=[(DEFAULT_ENTRY, STT_FUNC), ("extra", STT_FUNC)],
rela=((51, 0),),
)
)
assert cli_main([str(elf_path)]) == 1
out = capsys.readouterr().out
for needle in (".ctors", "malloc", "extra", "TLSDESC"):
assert needle in out