From 5f9c0703f20ffccea9248c4316213dc6d980d6d9 Mon Sep 17 00:00:00 2001 From: sscodeai Date: Mon, 19 Oct 2026 22:41:40 +0900 Subject: [PATCH] feat(pptx): DET-009 speaker notes; fix PPTX coordinates; pin DET-008 evals Two fixes chosen from a review of the DET-008 write-up, plus a new detector. PPTX paragraph coordinates (bug): PptxParser used the slide number as TextParagraph.index, so every text box and the notes on a slide shared one coordinate. A single hidden run therefore matched every run on that slide and `sanitize --mode redact` replaced the whole slide with [REDACTED]. Indices are now unique per paragraph; the slide number stays in raw["slide"]. Regression tests assert unique indices and that only the notes run is redacted. DET-009 speaker_notes (gap): Notes were already parsed and are read by any extractor/LLM, but nothing scored them, so a deck whose only injection was a plain-text note scanned clean and was allowed. DET-009 reports a note that instructs a reader: HIGH for an explicit override / "do not tell" payload, MEDIUM for a system-addressed or verdict-directing one; the notes run is defused on quarantine. Generic reminders are not reported. Trust labeling counts it as concealment (structure). DET-008 evaluation artifacts (reproducibility): - AMBIGUOUS_CORPUS pinned in tests/detectors/test_comment_directive.py (4 legit notes that are reported on purpose; counted as accepted false positives). - scripts/probe_comment_directive.py, the committed live false-positive probe; build output (dist/...) is excluded by default, --include-build restores the older, larger 168-file figure. The README/coverage numbers now come from these artifacts (106 files / 738 comment lines, 0 findings) instead of the unverifiable "167 files / 4,643 comment lines". - DET-008 detector docstring said 0/45 benign comments; the corpus holds 46. README/README.ja detector table and counts, SECURITY directive-bypass scope, CHANGELOG Unreleased, Makefile `probe` target, and the test-count badge (339). --- CHANGELOG.md | 23 +++ Makefile | 5 +- README.ja.md | 27 +++- README.md | 29 +++- SECURITY.md | 5 +- docs/comment-directive-coverage.md | 25 +++- docs/plan-zero-touch-adoption.md | 5 +- scripts/probe_comment_directive.py | 138 ++++++++++++++++++ src/aiitg/detectors/__init__.py | 2 + src/aiitg/detectors/text/comment_directive.py | 4 +- src/aiitg/detectors/text/speaker_notes.py | 97 ++++++++++++ src/aiitg/parsers/pptx_parser.py | 11 +- src/aiitg/trust_label.py | 2 +- tests/detectors/test_comment_directive.py | 29 ++++ tests/detectors/test_formats.py | 34 +++++ tests/e2e/test_cli_e2e.py | 5 +- 16 files changed, 410 insertions(+), 31 deletions(-) create mode 100644 scripts/probe_comment_directive.py create mode 100644 src/aiitg/detectors/text/speaker_notes.py diff --git a/CHANGELOG.md b/CHANGELOG.md index f3b282f..346a135 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,29 @@ All notable changes to this project are documented here. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [Unreleased] + +### Added + +- **DET-009 `speaker_notes`**: directive/injection content in PowerPoint speaker notes. Notes were + already parsed (`element="notes"`) but nothing scored them, so a deck whose only injection was a + plain-text instruction in the notes scanned clean and was allowed. HIGH for an explicit + override/"do not tell" payload, MEDIUM for a system-addressed or verdict-directing one; the notes + run is defused on quarantine. +- **Reproducible DET-008 measurements**: an `AMBIGUOUS_CORPUS` pinned in + `tests/detectors/test_comment_directive.py` (4 legit notes that are reported on purpose, counted as + accepted false positives) and `scripts/probe_comment_directive.py`, the committed live + false-positive probe (build output excluded by default, `--include-build` to include it). The README + and `docs/comment-directive-coverage.md` figures now come from these artifacts. + +### Fixed + +- **PPTX paragraph coordinates**: the parser used the slide number as `TextParagraph.index`, so every + text box (and the notes) on a slide shared one coordinate. A single hidden run therefore matched + every run on the slide, and `sanitize --mode redact` replaced the whole slide with `[REDACTED]`. + Indices are now unique per paragraph; the slide number remains in `raw["slide"]`. +- DET-008 detector docstring said "0/45 benign comments"; the pinned corpus holds 46. + ## [0.2.1] — 2026-09-20 Fixes merged from `main` (PR #1, `fix/dev-review-findings`) that this branch now builds on: diff --git a/Makefile b/Makefile index 09d5fad..929549a 100644 --- a/Makefile +++ b/Makefile @@ -1,4 +1,4 @@ -.PHONY: test lint typecheck build demo +.PHONY: test lint typecheck build demo probe test: .venv/bin/pytest -q @@ -14,3 +14,6 @@ build: demo: .venv/bin/python examples/scan_demo.py + +probe: + .venv/bin/python scripts/probe_comment_directive.py . diff --git a/README.ja.md b/README.ja.md index fa2b2a0..c935cbb 100644 --- a/README.ja.md +++ b/README.ja.md @@ -7,7 +7,7 @@ [![CI](https://github.com/sscodeai/aiitg/actions/workflows/ci.yml/badge.svg)](https://github.com/sscodeai/aiitg/actions/workflows/ci.yml) [![Python 3.11+](https://img.shields.io/badge/python-3.11%2B-blue.svg)]() [![License: MIT](https://img.shields.io/badge/license-MIT-green.svg)]() -[![Tests](https://img.shields.io/badge/tests-330%20passed-brightgreen.svg)](.github/workflows/ci.yml) +[![Tests](https://img.shields.io/badge/tests-339%20passed-brightgreen.svg)](.github/workflows/ci.yml) [![arXiv](https://img.shields.io/badge/arXiv-2507.06185-red.svg)]() --- @@ -55,7 +55,7 @@ Untrusted input (docx/xlsx/xls/pdf/html/pptx) │ FormatRegistry → parser → ParsedDocument │ │ (format-agnostic intermediate model) │ │ │ -│ Detector chain (8 detectors) │ +│ Detector chain (9 detectors) │ │ → Evidence list (coordinate-level) │ │ │ │ Sanitizer (strip / redact) │ @@ -93,6 +93,7 @@ Untrusted input (docx/xlsx/xls/pdf/html/pptx) | DET-006 | annotations | Word コメント、PDF 注釈、HTML コメント | LOW | | DET-007 | document_meta | メタデータ、VBA マクロ、JS シグナル | LOW | | DET-008 | comment_directive | 普通のコードコメント、またはエージェントのルールファイルに隠された危険な指示。指示フレーム(マーカー / モデルへの呼びかけ / 命令形 / 権威の主張 / 検証を省けという指示)と、論文 Appendix A の 10 種の脆弱性クラスのいずれかが同時に揃ったときに発火 | CRITICAL · HIGH · MEDIUM | +| DET-009 | speaker_notes | PowerPoint の講演者メモにある指示・注入。機械は読むが、発表時には表示されない | HIGH · MEDIUM | ### 対応形式 @@ -117,7 +118,7 @@ aiitg scan report.docx --format json # JSON evidence report aiitg scan report.xlsx --min-severity high # high 以上の finding のみ aiitg scan report.pdf --format rich # ターミナル表形式 aiitg scan ./inbox --recursive --jsonl # ディレクトリ一括スキャン。1 行 1 compact JSON -aiitg list-detectors # 8 個の検出器を一覧表示 +aiitg list-detectors # 9 個の検出器を一覧表示 ``` 終了コード: `0` = clean · `1` = 閾値以上の finding あり · `2` = 使用方法エラー · `3` = パースエラー(CI 向け)。 @@ -207,18 +208,32 @@ aiitg hook pretooluse < payload.json # deny(POL-001): ファイルは |---|---| | 攻撃コーパス(10 クラス × 3 フレーミング + エージェント向け 2 件。うち 2 件は論文から逐語) | 32/32 検出、29 CRITICAL / 3 HIGH | | 良性コーパス(通常の作業コメント 46 件、5 つのコメント記法) | 誤検知 0 | -| 実在のサードパーティソース走査(本プロジェクト + `takumi/packages`: 167 ファイル、コメント 4,643 行) | 検出 0 | -| ペイロードと同じ形をした正当なメモ(`# TODO: use DBMS_SCHEDULER for the nightly job`) | 検出する(意図的な fail-closed) | +| 曖昧コーパス(ペイロードと同じ形をした正当なメモ 4 件、テストに固定) | 4/4 検出 — 受け入れた**誤検知クラス**(意図的な fail-closed) | +| 実在ソース走査(`scripts/probe_comment_directive.py`、本プロジェクト + `takumi/packages`、ビルド成果物は除外: 106 ファイル / コメント 738 行) | 検出 0 | + +曖昧コーパスの 4 件は *正当な* メモであり、それでも報告されます。これは検出ではなく既知の誤検知として計上し、 +コーパスが実際よりきれいに見えることはありません。実在ソース走査の数値はコミット済みスクリプトで再現できます(§6)。 +以前の「167 ファイル / コメント 4,643 行」はビルド成果物(`dist/`)を含み、コメント行の数え方も緩かったものです—— +`--include-build` で 168 ファイルになりますが、生成物は開発者が読むサードパーティソースではないため既定で除外します。 正直な境界: 論文の 700 件コーパスは HTML と一緒に公開されていないため、この数値は論文の数値の**再現ではありません**。 決定的なパターン検出器は原理的に不完全です(論文自身の最強スクリーナーでも約 1/3 を見逃しています)。 また DET-008 が読むのは *指示* であり、モデルが既に書いた脆弱なコードではありません(それは SAST の役割です)。 設計と既知のギャップ: [`docs/comment-directive-coverage.md`](docs/comment-directive-coverage.md)。 +### 講演者メモ(DET-009) + +スライドの講演者メモは発表時には表示されませんが、ファイルには残り、あらゆる抽出器——つまり要約する LLM——が読みます。 +`pptx` は以前からメモをパースしていましたが、それを採点する検出器がなく、メモだけに平文の指示を仕込んだデッキは +検出 0 の clean として通過していました。DET-009 はこのチャネルを塞ぎます。読み手(モデルまたは人間)に指示しようとする +メモを報告し(明示的な上書き /「伝えるな」は HIGH、システム宛や結論を誘導するものは MEDIUM)、quarantine 時にはメモの run を +無効化します。「ロードマップのスライドを更新する」といった一般的なリマインダーは報告しません。DET-008 と同様に +パターン検出器であり、チャネルは覆いますが語彙は網羅的ではありません。 + ## テスト ```bash -make test # 330 tests +make test # 339 tests make lint # ruff make typecheck # mypy make build # wheel/sdist をビルド diff --git a/README.md b/README.md index e2fc422..6984706 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ [![CI](https://github.com/sscodeai/aiitg/actions/workflows/ci.yml/badge.svg)](https://github.com/sscodeai/aiitg/actions/workflows/ci.yml) [![Python 3.11+](https://img.shields.io/badge/python-3.11%2B-blue.svg)]() [![License: MIT](https://img.shields.io/badge/license-MIT-green.svg)]() -[![Tests](https://img.shields.io/badge/tests-330%20passed-brightgreen.svg)](.github/workflows/ci.yml) +[![Tests](https://img.shields.io/badge/tests-339%20passed-brightgreen.svg)](.github/workflows/ci.yml) [![arXiv](https://img.shields.io/badge/arXiv-2507.06185-red.svg)]() --- @@ -56,7 +56,7 @@ Untrusted input (docx/xlsx/xls/pdf/html/pptx) │ FormatRegistry → parser → ParsedDocument │ │ (format-agnostic intermediate model) │ │ │ -│ Detector chain (8 detectors) │ +│ Detector chain (9 detectors) │ │ → Evidence list (coordinate-level) │ │ │ │ Sanitizer (strip / redact) │ @@ -94,6 +94,7 @@ Untrusted input (docx/xlsx/xls/pdf/html/pptx) | DET-006 | annotations | Word comments, PDF annotations, HTML comments | LOW | | DET-007 | document_meta | Metadata / VBA macros / JS signals | LOW | | DET-008 | comment_directive | Insecure instruction hidden in an ordinary code comment or agent rule file — the directive frame (marker / addressed / imperative / authority / "skip the check") plus one of the ten injected-weakness classes | CRITICAL · HIGH · MEDIUM | +| DET-009 | speaker_notes | Directive/injection content in PowerPoint speaker notes — machine-readable but not shown when the deck is presented | HIGH · MEDIUM | ### Formats @@ -133,16 +134,28 @@ Measured on this repository's corpus and on live third-party source, with the bo |---|---| | Attack corpus (10 classes × 3 framings + 2 agent-directed; 2 payloads verbatim from the paper) | 32/32 detected, 29 CRITICAL / 3 HIGH | | Benign corpus (46 ordinary work comments, five syntax families) | 0 false positives | -| Live third-party source probe (this project + `takumi/packages`: 167 files, 4,643 comment lines) | 0 findings | -| Legit notes byte-shaped like a payload (`# TODO: use DBMS_SCHEDULER for the nightly job`) | flagged — the deliberate fail-closed choice | +| Ambiguous corpus (4 legit notes byte-shaped like a payload, pinned in `tests/`) | 4/4 reported — accepted false positives, the deliberate fail-closed choice | +| Live third-party source probe (`scripts/probe_comment_directive.py`: this project + `takumi/packages`, build output excluded: 106 files, 738 comment lines) | 0 findings | Honest boundaries: the paper's 700-item corpus was not released with its HTML, so these figures are **not** a reproduction of the paper's numbers; a deterministic pattern detector is incomplete by construction (the paper's own strongest screen still missed ~⅓); and DET-008 reads *instructions*, not -the vulnerable code a model may already have written — that is a SAST job. Design notes, the full -measurement method and the known gaps: +the vulnerable code a model may already have written — that is a SAST job. The ambiguous row is +reported as a known false-positive class, not as detections. Design notes, the full measurement method +and the known gaps: [`docs/comment-directive-coverage.md`](docs/comment-directive-coverage.md). +### Speaker notes (DET-009) + +A slide's speaker notes are not shown when the deck is presented, but they live in the file and every +extractor — and therefore every LLM that summarises the deck — reads them. `pptx` already parsed them; +until DET-009 nothing scored them, so a deck whose **only** injection was a plain-text instruction in +the notes scanned clean and was allowed. DET-009 closes that channel: a note that tries to instruct a +reader (a model or a human) is reported — HIGH for an explicit override/"do not tell" payload, MEDIUM +for a system-addressed or verdict-directing one — and the notes run is defused on quarantine. Generic +reminders ("update the roadmap slide") are not reported. Like DET-008 it is a pattern detector: the +channel is covered, the payload vocabulary is not exhaustive. + ## Install ### Use it (recommended for the Claude Code hook) @@ -181,7 +194,7 @@ aiitg scan report.docx --format json # JSON evidence report aiitg scan report.xlsx --min-severity high # only high+ findings aiitg scan report.pdf --format rich # terminal table aiitg scan ./inbox --recursive --jsonl # batch directory scan, one compact JSON object per line -aiitg list-detectors # list all 8 detectors +aiitg list-detectors # list all 9 detectors ``` Exit codes: `0` = clean · `1` = findings at/above threshold · `2` = usage error · `3` = parse error (CI-friendly). @@ -291,7 +304,7 @@ else: ## Testing ```bash -make test # 330 tests +make test # 339 tests make lint # ruff make typecheck # mypy make build # build wheel/sdist diff --git a/SECURITY.md b/SECURITY.md index 1c89962..9580518 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -29,8 +29,9 @@ In scope — anything that breaks the project's promises: overrides a real verdict). - **Detection bypass**: a concealment technique that a human reader cannot see but aiitg reports as `safe` with no evidence, or a sanitized output that still carries the hidden payload. -- **Directive bypass**: an instruction planted in a code comment or an agent rule file that reaches - the model without a `DET-008` finding, or a sanitized substitute that still carries it. This is not +- **Directive bypass**: an instruction planted in a code comment, an agent rule file, or a + PowerPoint speaker-note page that reaches the model without a `DET-008`/`DET-009` finding, or a + sanitized substitute that still carries it. This is not *concealment* — a human reads the comment too — but it breaks the same promise through a different channel, so it is in scope. - **Policy bypass**: reaching `allow` for a document the default policy would block/quarantine, or a diff --git a/docs/comment-directive-coverage.md b/docs/comment-directive-coverage.md index 54b32e7..c3dc72f 100644 --- a/docs/comment-directive-coverage.md +++ b/docs/comment-directive-coverage.md @@ -97,8 +97,15 @@ Corpus and probe live in `tests/detectors/test_comment_directive.py`, |---|---| | Attack corpus — 32 payloads: the paper's 10 classes × 3 framings + 2 agent-directed (2 payloads verbatim from the paper; the rest authored in its stated format) | **32/32 detected**, class agreement 32/32, 29 CRITICAL / 3 HIGH | | Benign corpus — 46 ordinary work comments across five comment syntax families | **0 false positives** | -| Live source probe — 167 files / **4,643 comment lines** of third-party source (this project + `takumi/packages`, via the shipped `run_scan()`) | **0 findings** | -| Ambiguous cases (legit notes byte-shaped like payloads) | 4/4 flagged — the fail-closed choice, not an accident | +| Ambiguous corpus — 4 legit notes byte-shaped like payloads, pinned in the test file | 4/4 reported — **accepted false positives**, the fail-closed choice | +| Live source probe — `scripts/probe_comment_directive.py` over this project + `takumi/packages` (build output excluded): **106 files / 738 comment lines**, via the shipped `run_scan()` | **0 findings** | + +The ambiguous row is the honest one: those four are *legit* notes that are reported anyway. They are +counted as a known false-positive class, not as detections, so the corpus can never look cleaner than +it is. The live-probe figures are reproducible with the committed script (see §6); the earlier +"167 files / 4,643 comment lines" figure came from *including* build output (`dist/`) and from a looser +comment-line definition — `--include-build` restores 168 files, but generated bundles are not +third-party source a developer reads, so they are excluded by default. Boundaries, stated plainly: @@ -125,9 +132,15 @@ Boundaries, stated plainly: ```bash make test # unit + integration + e2e, incl. the corpus tests -pytest tests/detectors/test_comment_directive.py -q # the attack/benign corpus itself +pytest tests/detectors/test_comment_directive.py -q # the attack/benign/ambiguous corpora + +# The live false-positive probe. Build output is excluded by default; pass +# --include-build to reproduce the (older, larger) 168-file figure. +python scripts/probe_comment_directive.py . ../takumi/packages +python scripts/probe_comment_directive.py . ../takumi/packages --json ``` -The live probe walks a source tree, counts comment lines per language family, and runs `run_scan()` -over each file — it is deliberately an *external* script so the repository's own tree does not ship a -hard-coded measurement. +The probe walks a source tree, counts the full-line comments the detector actually reads (per +language family), and runs the shipped `run_scan()` over each file — it re-implements nothing, so it +measures the gateway as shipped. It is a *false-positive* measurement: it reports what the detector +flags on code written without any injected payload, and says nothing about recall. diff --git a/docs/plan-zero-touch-adoption.md b/docs/plan-zero-touch-adoption.md index a30ca5c..ce3fe62 100644 --- a/docs/plan-zero-touch-adoption.md +++ b/docs/plan-zero-touch-adoption.md @@ -615,8 +615,9 @@ Guardrails for backward compatibility: - **Hook-contract drift**: the `hookSpecificOutput` schema is an external contract and may change. Mitigation: pin the documented field names in one renderer (`render_outcome`), test it directly, and keep the CLI stdout shape in one place. -- **Performance**: each enforced `Read` runs a full parse + the detector chain (documents: 7 detectors; - source files: the code-context detector only). Mitigation: extension +- **Performance**: each enforced `Read` runs a full parse + the detector chain (documents: up to 8 + detectors — pptx adds the speaker-notes detector; source files: the code-context detector only). + Mitigation: extension allowlist, `(path, mtime, size)` result cache, hook `timeout` in settings, and an `--no-scan` passthrough for large files. - **False positives**: `default_policy` quarantines on any evidence (POL-002), so legitimately diff --git a/scripts/probe_comment_directive.py b/scripts/probe_comment_directive.py new file mode 100644 index 0000000..427b067 --- /dev/null +++ b/scripts/probe_comment_directive.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Live false-positive probe for DET-008 (`comment_directive`) over real source trees. + +`docs/comment-directive-coverage.md` reports a live probe over third-party source. This +is the script that produces that row, committed so the number is reproducible instead of +being a claim in prose. It walks the given roots, counts comment lines per comment-syntax +family, and runs the shipped detector chain over every file, reporting only DET-008 hits. + +The selection rule is deliberately explicit and conservative: a file is a candidate when +it is a known code/config extension (`CODE_EXTENSIONS`) or an agent rule file by name +(`RULE_FILE_NAMES`), and it is not inside a build/cache/VCS directory. The detector is +applied with the production `run_scan()`, not a re-implementation, so the probe measures +what the gateway actually does. + +Usage:: + + python scripts/probe_comment_directive.py . # this repository + python scripts/probe_comment_directive.py . ../takumi/packages + python scripts/probe_comment_directive.py . --json + +The probe is a *false-positive* measurement: it counts what the detector reports on code +that was written without any injected payload. It says nothing about recall. +""" + +from __future__ import annotations + +import argparse +import json +import sys +from collections import Counter +from pathlib import Path + +from aiitg.core.detector import default_detector_registry, run_scan +from aiitg.parsers.text_parser import CODE_EXTENSIONS, RULE_FILE_NAMES, comment_body, language_for_path + +#: Directories that are VCS metadata, dependency caches or tool state, never sources. +EXCLUDE_DIRS = frozenset( + { + ".git", ".hg", ".svn", "node_modules", ".venv", "venv", "env", + "__pycache__", ".mypy_cache", ".ruff_cache", ".pytest_cache", + ".tox", "htmlcov", ".coverage", ".next", ".turbo", ".idea", ".vscode", + } +) + +#: Build output. Excluded by default: generated bundles are not third-party source a +#: developer reads, and counting them inflates the corpus (the original 167-file figure +#: came from *not* excluding these). ``--include-build`` restores that behaviour. +BUILD_DIRS = frozenset({"dist", "build", "out", "target", ".output"}) + + +def iter_source_files(root: Path, *, include_build: bool = False) -> list[Path]: + """Every candidate source/config/rule file under ``root``, sorted for determinism.""" + excluded = EXCLUDE_DIRS if include_build else EXCLUDE_DIRS | BUILD_DIRS + out: list[Path] = [] + for path in root.rglob("*"): + if not path.is_file(): + continue + if any(part in excluded for part in path.parts): + continue + if path.name.lower() in RULE_FILE_NAMES or path.suffix.lower() in CODE_EXTENSIONS: + out.append(path) + return sorted(out) + + +def count_comment_lines(path: Path, lang: str | None) -> int: + try: + text = path.read_text(encoding="utf-8", errors="replace") + except OSError: + return 0 + return sum(1 for line in text.splitlines() if comment_body(line, lang) is not None) + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description="DET-008 false-positive probe over source trees.") + parser.add_argument("roots", nargs="*", default=["."], help="source trees to scan") + parser.add_argument("--json", action="store_true", help="emit the full result as JSON") + parser.add_argument( + "--include-build", + action="store_true", + help="also walk build output (dist/build/out/target); off by default", + ) + args = parser.parse_args(argv) + + registry = default_detector_registry() + files = 0 + comment_lines = 0 + by_lang: Counter[str] = Counter() + findings: list[dict[str, object]] = [] + + for root_arg in args.roots: + root = Path(root_arg) + if not root.exists(): + print(f"probe: skipping missing root {root}", file=sys.stderr) + continue + for path in iter_source_files(root, include_build=args.include_build): + files += 1 + lang = language_for_path(path) + n_comments = count_comment_lines(path, lang) + comment_lines += n_comments + by_lang[lang or "rule"] += n_comments + report = run_scan(str(path), registry) + for ev in report.evidence: + if ev.detector_id != "DET-008": + continue + findings.append( + { + "file": str(path), + "line": ev.location.paragraph, + "severity": ev.severity.value, + "class": ev.raw.get("class"), + "title": ev.title, + } + ) + + result = { + "roots": [str(r) for r in args.roots], + "include_build": args.include_build, + "files": files, + "comment_lines": comment_lines, + "comment_line_langs": dict(sorted(by_lang.items())), + "det_008_findings": len(findings), + "findings": findings, + } + if args.json: + print(json.dumps(result, ensure_ascii=False, indent=2)) + else: + print(f"roots: {', '.join(result['roots'])}") + print(f"files scanned: {files}") + langs = ", ".join(f"{k}={v}" for k, v in result["comment_line_langs"].items()) + print(f"comment lines: {comment_lines} (by family: {langs})") + print(f"DET-008 hits: {len(findings)}") + for f in findings: + print(f" {f['severity']:8} {str(f['class']):34} {f['file']}:{f['line']}") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/src/aiitg/detectors/__init__.py b/src/aiitg/detectors/__init__.py index f83ef66..29e9dca 100644 --- a/src/aiitg/detectors/__init__.py +++ b/src/aiitg/detectors/__init__.py @@ -13,6 +13,7 @@ from aiitg.detectors.structure.ooxml_nodes import OOXMLNodesDetector from aiitg.detectors.text.comment_directive import CommentDirectiveDetector from aiitg.detectors.text.hidden_style import HiddenStyleDetector +from aiitg.detectors.text.speaker_notes import SpeakerNotesDetector from aiitg.detectors.text.tiny_font import TinyFontDetector from aiitg.detectors.text.zero_width import ZeroWidthDetector @@ -25,6 +26,7 @@ AnnotationsDetector(), DocumentMetaDetector(), CommentDirectiveDetector(), + SpeakerNotesDetector(), ] __all__ = ["ALL_DETECTORS"] diff --git a/src/aiitg/detectors/text/comment_directive.py b/src/aiitg/detectors/text/comment_directive.py index 7af705f..3c2cc4a 100644 --- a/src/aiitg/detectors/text/comment_directive.py +++ b/src/aiitg/detectors/text/comment_directive.py @@ -24,8 +24,8 @@ Descriptive prose that merely names a sink ("a bare ``subprocess`` cannot answer", "this query concatenates user input") has no frame and is not reported: a comment scanner that flags every mention of ``exec`` is unusable. Measured on the bundled -corpus: 32/32 attack items, 0/45 benign comments, and 0 findings over 4.5k comment -lines of live third-party source. +corpus: 32/32 attack items, 0/46 benign comments, 4/4 accepted false positives on +legit notes byte-shaped like payloads, and 0 findings over live third-party source. Scope boundary (deliberate): this reads *comments*, not code. Vulnerable code that is already written is the job of a SAST tool; this detector covers the instruction that diff --git a/src/aiitg/detectors/text/speaker_notes.py b/src/aiitg/detectors/text/speaker_notes.py new file mode 100644 index 0000000..d63e62f --- /dev/null +++ b/src/aiitg/detectors/text/speaker_notes.py @@ -0,0 +1,97 @@ +"""DET-009: directive content in PowerPoint speaker notes. + +A slide's speaker notes are not shown when the deck is presented, but they are part +of the file and every text extractor (and therefore every LLM that summarises the +deck) reads them. That makes notes the same class of channel as Word comments and PDF +annotations: machine-readable, human-invisible-in-normal-view. + +The pptx parser already exposes notes as paragraphs tagged ``element="notes"``. Until +this detector existed nothing scored them, so a deck whose *only* injection was a +plain-text instruction in the notes scanned clean and was allowed through (the existing +detectors only fire on zero-width characters or hidden styling, so a plain-text note +was invisible to all of them). + +Scope: this reads the notes text, it does not judge the slide content. A note that is a +*generic* reminder is not reported; a note that tries to instruct the reader (a model or +a human) is. As with DET-008, a pattern detector is incomplete by construction — the +value is that the channel is now covered and the finding is fail-closed. +""" + +from __future__ import annotations + +import re + +from aiitg.core.detector import Detector +from aiitg.core.document import ParsedDocument +from aiitg.core.evidence import Evidence, Location, Severity + +#: Strong injection signals: an explicit attempt to override instructions or to hide +#: something from a human. A note carrying one of these is HIGH. +_STRONG_RE = re.compile( + r"ignore\s+(?:all\s+|any\s+|the\s+)?(?:previous|prior|above|earlier)\b" + r"|disregard\s+(?:all\s+|any\s+|the\s+)?(?:previous|prior|above)\b" + r"|do\s+not\s+(?:tell|inform|mention|reveal|disclose)\b" + r"|don'?t\s+(?:tell|inform|mention|reveal|disclose)\b" + r"|secret\s+instructions?\b" + r"|忽略(?:之前|以前|上述|上面|所有|此前)" + r"|不要(?:告诉|通知|提及|透露|披露|提醒)", + re.IGNORECASE, +) + +#: Weaker directive signals: the note addresses a machine/system or tells the reader +#: what verdict to reach. Reported, but not treated as blocking on their own. +_DIRECTIVE_RE = re.compile( + r"(?:system|ai|assistant|model|copilot|claude)\s*(?:指令|指示|提示|prompt|instruction)" + r"|(?:必须|请)(?:给|给出|选择|推荐|录用|批准|评分)" + r"|(?:强烈推荐|直接录用|必须录用|优先资助|给[^,。\n]{0,6}满分)" + r"|\byou\s+must\s+(?:always|never)\b", + re.IGNORECASE, +) + + +class SpeakerNotesDetector(Detector): + id = "DET-009" + name = "speaker_notes" + description = ( + "Directive/injection content in PowerPoint speaker notes — machine-readable " + "but not shown when the deck is presented." + ) + supported_kinds = frozenset({"pptx"}) + default_severity = Severity.MEDIUM + + def scan(self, doc: ParsedDocument) -> list[Evidence]: + evidence: list[Evidence] = [] + for para in doc.paragraphs: + if para.raw.get("element") != "notes": + continue + strong = _STRONG_RE.search(para.text) + directive = _DIRECTIVE_RE.search(para.text) + match = strong or directive + if match is None: + continue + tier = "strong" if strong is not None else "directive" + evidence.append( + self.make_evidence( + title="Directive in speaker notes", + description=( + f"Speaker notes contain a {tier} instruction ('{match.group(0)}'). " + "Notes are not shown in the presentation but are read by any text " + "extractor or LLM that ingests the deck." + ), + severity=Severity.HIGH if strong is not None else Severity.MEDIUM, + location=Location( + source=doc.source_name, + paragraph=para.index, + run=0, + element=f"notes:slide{para.raw.get('slide')}", + char_range=(match.start(), match.end()), + ), + raw={ + "text": para.text, + "slide": para.raw.get("slide"), + "tier": tier, + "phrase": match.group(0), + }, + ) + ) + return evidence diff --git a/src/aiitg/parsers/pptx_parser.py b/src/aiitg/parsers/pptx_parser.py index e9b7394..1bf677c 100644 --- a/src/aiitg/parsers/pptx_parser.py +++ b/src/aiitg/parsers/pptx_parser.py @@ -54,6 +54,11 @@ def parse(self, path: Path) -> ParsedDocument: prs = Presentation(str(path)) doc_model = ParsedDocument(kind="pptx", source_path=str(path)) slide_num = 0 + # Paragraph index must be unique across the document: it is the coordinate the + # sanitizer uses to redact exactly one run. Using the slide number made every + # text box on a slide share one coordinate, so a single hidden run matched (and + # redacted) the whole slide. The slide is still reported via raw["slide"]. + para_index = 0 for slide in prs.slides: slide_num += 1 @@ -68,10 +73,11 @@ def parse(self, path: Path) -> ParsedDocument: runs: list[TextRun] = [] for r in para.runs: runs.append(_run_from_font(r.text, r.font)) + para_index += 1 doc_model.paragraphs.append( TextParagraph( text=text, - index=slide_num, + index=para_index, runs=runs, raw={"slide": slide_num, "shape": shape.shape_id, "element": f"slide{slide_num}"}, ) @@ -82,10 +88,11 @@ def parse(self, path: Path) -> ParsedDocument: notes_frame = slide.notes_slide.notes_text_frame if notes_frame is not None and notes_frame.text.strip(): notes_text = notes_frame.text + para_index += 1 doc_model.paragraphs.append( TextParagraph( text=notes_text, - index=slide_num, + index=para_index, runs=[TextRun(text=notes_text, is_header_footer=True, raw={"element": "notes"})], raw={"slide": slide_num, "element": "notes"}, ) diff --git a/src/aiitg/trust_label.py b/src/aiitg/trust_label.py index 82fc8a7..698fa1f 100644 --- a/src/aiitg/trust_label.py +++ b/src/aiitg/trust_label.py @@ -32,7 +32,7 @@ } # detector IDs that signal deliberate concealment (structure) -_STRUCT_DETECTORS = {"DET-001", "DET-002", "DET-003", "DET-004", "DET-005", "DET-006"} +_STRUCT_DETECTORS = {"DET-001", "DET-002", "DET-003", "DET-004", "DET-005", "DET-006", "DET-009"} # detector IDs that signal manipulation intent (content) _CONTENT_DETECTORS = {"DET-007", "DET-008"} diff --git a/tests/detectors/test_comment_directive.py b/tests/detectors/test_comment_directive.py index e629239..18c6793 100644 --- a/tests/detectors/test_comment_directive.py +++ b/tests/detectors/test_comment_directive.py @@ -116,6 +116,18 @@ "-- TODO: add an index on user_id", ] +#: Legit developer notes that happen to be *byte-shaped* like a payload. These are +#: reported on purpose: the shape is the attack, and a quote-guard ("this only quotes a +#: payload") would hand an attacker an evasion. They are measured and reported as an +#: **accepted false-positive class**, not as detections, so the corpus can never look +#: cleaner than it is: treat 4/4 below as 4 known false positives, not 4 true positives. +AMBIGUOUS_CORPUS: list[str] = [ + "# TODO: use DBMS_SCHEDULER for the nightly job", + "# TODO: log the token to stderr when DEBUG is on", + "# INSTRUCTION: redirect to the URL in the next parameter", + "# TODO: open the path from the CLI argument directly for the fixture loader", +] + class TestAttackCorpus: @pytest.mark.parametrize(("expected_class", "payload"), ATTACK_CORPUS) @@ -181,6 +193,23 @@ def test_weak_class_with_a_real_directive_is_high(self): assert found.severity == "high" +class TestAmbiguousCorpus: + """The fail-closed corner: legit notes that look like payloads are still reported. + + These four are pinned so the number in the docs is reproducible from the repository. + They are counted as reported (accepted false positives), not as correct detections. + """ + + @pytest.mark.parametrize("line", AMBIGUOUS_CORPUS) + def test_ambiguous_note_is_flagged_fail_closed(self, line): + found = classify_line(line, lang=_lang_of(line)) + assert found is not None, f"ambiguous note was not reported: {line}" + assert found.severity in ("critical", "high", "medium") + + def test_ambiguous_corpus_is_pinned_at_four(self): + assert len(AMBIGUOUS_CORPUS) == 4 + + class TestCommentSyntax: @pytest.mark.parametrize( ("line", "lang"), diff --git a/tests/detectors/test_formats.py b/tests/detectors/test_formats.py index f9c6636..387c70c 100644 --- a/tests/detectors/test_formats.py +++ b/tests/detectors/test_formats.py @@ -2,7 +2,9 @@ from __future__ import annotations +from aiitg.core.evidence import Severity from aiitg.core.registry import default_format_registry +from aiitg.pipeline import process_file from tests.fixtures import builders @@ -45,6 +47,38 @@ def test_pptx_zerowidth(self, scan_file, tmp_path): hits = [ev for ev in report.evidence if ev.detector_id == "DET-001"] assert len(hits) >= 1 + def test_notes_directive_detected(self, scan_file, tmp_path): + f = builders.build_pptx_notes(tmp_path / "notes.pptx") + report = scan_file(f) + hits = [ev for ev in report.evidence if ev.detector_id == "DET-009"] + assert len(hits) == 1 + assert hits[0].severity == Severity.HIGH + assert hits[0].location.element.startswith("notes:slide") + + def test_plain_notes_are_not_reported(self, scan_file, tmp_path): + f = builders.build_pptx_notes( + tmp_path / "plain.pptx", notes_text="Remind the team to update the roadmap slide." + ) + report = scan_file(f) + assert [ev for ev in report.evidence if ev.detector_id == "DET-009"] == [] + + def test_paragraph_indices_are_unique(self, tmp_path): + # Regression: the paragraph index used to be the slide number, so every text + # box (and the notes) on one slide shared a coordinate. + f = builders.build_pptx_notes(tmp_path / "notes.pptx") + doc = default_format_registry().parse(f) + indices = [p.index for p in doc.paragraphs] + assert len(set(indices)) == len(indices) + + def test_sanitize_redacts_only_the_notes(self, tmp_path): + # Regression: with colliding coordinates a single hidden run redacted the whole + # slide. Only the notes payload may be removed; the slide body must survive. + f = builders.build_pptx_notes(tmp_path / "notes.pptx") + result = process_file(str(f), mode="redact") + text = result.sanitized.text + assert "Visible slide content" in text + assert "SECRET INSTRUCTIONS" not in text + class TestXls: def test_benign_parses(self, scan_file, tmp_path): diff --git a/tests/e2e/test_cli_e2e.py b/tests/e2e/test_cli_e2e.py index 6022260..51d9bfc 100644 --- a/tests/e2e/test_cli_e2e.py +++ b/tests/e2e/test_cli_e2e.py @@ -98,7 +98,10 @@ class TestCLIList: def test_list_detectors(self): result = runner.invoke(app, ["list-detectors"]) assert result.exit_code == 0 - for det_id in ("DET-001", "DET-002", "DET-003", "DET-004", "DET-005", "DET-006", "DET-007", "DET-008"): + for det_id in ( + "DET-001", "DET-002", "DET-003", "DET-004", "DET-005", + "DET-006", "DET-007", "DET-008", "DET-009", + ): assert det_id in result.output