Files
msd-core/scripts/prompt-injection-scan.sh
Tom Boucher 27aa40f65e fix(#3023): stage pi's shared hook bundle outside pi's reserved hooks/ directory (#3175)
* test(#3023): failing-first guard — pi must not stage hooks in its reserved dir

pi reserves <configDir>/hooks as its deprecated extension location and warns
on every startup when it exists. Assert a pi install stages the shared hook
bundle under gsd-hooks/ instead, manifests it there, and never creates hooks/.

Also adds pi to the local-scope dir table in install-shared.cjs: pi was in
RUNTIME_META but not LOCAL_DIR_NAME, so scope:'local' resolved
path.join(root, undefined) and no local pi install could be exercised.

Fails before the fix. Verified via the remote runner.

* fix(#3023): stage pi's shared hook bundle outside pi's reserved hooks/ dir

pi reserves <configDir>/hooks as its now-deprecated extension location and
warns on every startup when that directory merely exists — checkDeprecatedExtensionDirs()
guards the warning with a bare existsSync(), unlike its tools/ sibling. GSD staged
its shared hook bundle exactly there, and pi's advised remediation (move it to
extensions/) would break the adapter's paths and expose GSD's .js helpers to pi's
extension auto-discovery.

The bundle directory name is now runtime-descriptor-driven: hostBehaviors
.sharedHooksDirName, defaulting to 'hooks' so all 18 other runtimes are
byte-identical. pi sets 'gsd-hooks'. The name is validated as a single path
segment — separators, dot-only segments, trailing dots, absolute paths, NUL,
and Windows reserved device names all fall back to the default, because the
value is joined onto a user's config root and written to.

Renamed in place rather than relocated: hook scripts resolve siblings via
__dirname/.., so a depth change would silently break them.

- install / uninstall / manifest sites all read the resolved name
- pi/gsd.cjs probes gsd-hooks then hooks, so dev checkouts and half-upgraded
  trees still resolve; the never-throws contract is preserved
- new migration 009 retires the legacy pi hooks/ dir on upgrade, using a new
  non-recursive remove-empty-dir engine primitive (rmdirSync only,
  symlink-refusing, containment-guarded); ADR-0008 amended accordingly
- fixes two latent name-dependencies the rename exposed: the stale-hook scan
  and the injection scanner's self-exclusion both hardcoded 'hooks'

Verified on the remote runner.

Closes #3023

* fix(#3023): close review findings and align emitted provenance with the rename

Adversarial review found two defects, and the remote runner found four
failure clusters. All fixed here.

Review BLOCKER — detect-custom-files was blind to the renamed bundle.
GSD_PREFIX_MANAGED_DIRS in gsd-tools.cjs hardcoded 'hooks', so for pi the
whole gsd-hooks/ tree was invisible to the custom-file scan and user-added
files there were never backed up before the next update's clean-install wipe.
The dir set now resolves via the .gsd-runtime marker plus the shipped
capability registry (never bin/install.js, which is not shipped into installed
trees), and falls back to scanning every known candidate when the runtime
cannot be determined — over-scanning is safe, under-scanning is the data loss.

Review MAJOR — the pi adapter bound to an empty bundle. resolveSharedHooksDir
accepted any directory, so an interrupted install left gsd-hooks/ winning over
a fully-staged legacy hooks/ and every hook silently no-opped. A candidate now
qualifies only if it is non-empty.

Remote-runner clusters:
- emitted-provenance had no rule for the gsd-hooks/ family; added two pi-scoped
  rules pointing at the same sources the existing hooks/ rules use. The table is
  total, so an unattributed family is a hard failure by design.
- pi tests in install-minimal-hooks and the install integration suite asserted
  the old layout; updated to derive the dir name from the descriptor rather than
  hardcoding either name.
- 19 unrelated-looking failures on node22 only were a leaked fs mock: t.after()
  runs in registration order, cleanup was registered before mock.restoreAll(),
  and node22's JS rimraf calls the public fs.rmdirSync while node24's native
  path does not — so the EACCES stub leaked process-wide on one lane. Restore
  now runs first.

Verified on the remote runner.

* fix(#3023): honor PI_CODING_AGENT_DIR, ack the rename ripple, fix expandTilde

pi resolves its agent dir as PI_CODING_AGENT_DIR ?? ~/<CONFIG_DIR_NAME>/agent
(packages/coding-agent/src/config.ts). GSD's pi descriptor declared an empty
configHome.env, so a user with that variable set had GSD installed where pi
never looks. Added the env name; the dot-home-nested resolver already handled
the override, so no resolver logic changed.

Also fixes expandTilde in the shared runtime-homes resolver, found while adding
that: it hardcoded os.homedir() and ignored the opts.home every caller threads,
so EVERY runtime's tilde-valued env override (claude, antigravity, windsurf, pi)
silently resolved against the real home. That is a correctness bug and a
test-escape hazard — a sandboxed test asserting on a tilde override reached the
developer's actual home directory. Now threaded through every branch; behavior
with no injected home is unchanged.

Adds the emitted-drift ack fragment for the 58 pi paths whose emitted location
moved with the rename. The provenance rules satisfy the totality gate; the
differential gate needs the ack because the hook sources are byte-unchanged —
only the installer's target directory moved. The two hook files this branch
genuinely edits stay attributed and are not double-acked.

Note on piConfig.configDir: it is read from pi's OWN installed package.json
(getPackageDir walks up from pi's __dirname), alongside piConfig.name — a
white-label setting for a redistributed pi fork, not a per-project user setting.
Documented accordingly rather than treated as an unsupported override.

Verified on the remote runner.

* fix(#3023): reject blank env overrides, pin adapter/descriptor parity

Three review findings, all fixed.

A whitespace-only config-dir override was accepted verbatim: the guard was
`if (val)`, falsy only for the empty string, so PI_CODING_AGENT_DIR='   '
resolved to a literal three-space directory name instead of falling back to the
descriptor default. Fixed across every env-consuming branch — dot-home,
dot-home-nested, all three xdg steps, and generic-agents-root — not just pi's.
Non-blank values are still never trimmed, so '~/My Agent Dir' keeps working.

pi/gsd.cjs's probe list and the descriptor were two independent sources of truth
for the bundle directory name; a future rename would have desynced them silently
and left every pi hook quiet with no error. The probe list stays deliberate — it
must resolve in a dev checkout and a half-upgraded tree, where the registry's
answer would be wrong — so this adds the parity assertion the repo's
generative-fix-divergence rule calls for: the descriptor value must be the FIRST
candidate, and the default must remain present.

Changeset body rewritten to cover the two later user-facing fixes it had not
caught up with.

Verified on the remote runner.

* chore(#3023): backfill changeset PR number

* fix(#3023): anchor injection-scan patterns and fix a macOS detection hole

CI's security job flagged CONTEXT.md:124 — pre-existing prose reading 'not the
same fact as a genuinely empty or absent one'. The match was the 'act as a'
INSIDE 'f-act as a': the pattern had no left word boundary, so any word ending
in act tripped it (fact, impact, contract, artifact, interact, redact,
abstract). My four-line CONTEXT.md edit dragged the latent false positive into
this PR because the scan is diff-scoped by file but reads whole files. Anchored
with (^|[^[:alnum:]]) rather than rewording maintainer-owned prose, which would
have left the class alive for the next PR touching any file saying 'fact as a'.

Auditing the rest of the list for the same class surfaced a real detection hole:
the eval/exec/Function patterns matched a quote via \x27, a GNU-grep-only hex
escape. BSD/macOS grep reads it as four literal characters, so single-quoted
eval('...')/exec('...') payloads were NEVER detected there while passing on
GNU-grep CI. Replaced with a literal apostrophe class.

Boundaries were added only where a real word-suffix collision exists; exec,
jailbreak, developer mode and the role-manipulation family were audited and
deliberately left unanchored. 22 new cases cover both directions — the false
positives now scan clean, and every real payload still fires, including the
quote/punctuation/start-of-line boundary forms.

Also builds this branch's injection test fixture at runtime instead of carrying
the literal phrase, so the payload keeps its teeth without tripping the scan.

Verified on the remote runner.

---------

Co-authored-by: sim <sim@local>
2026-08-07 13:41:21 -04:00

253 lines
9.9 KiB
Bash
Executable File

#!/usr/bin/env bash
# prompt-injection-scan.sh — Scan files for prompt injection patterns
#
# Usage:
# scripts/prompt-injection-scan.sh --diff origin/main # CI mode: scan changed .md files
# scripts/prompt-injection-scan.sh --file path/to/file # Scan a single file
# scripts/prompt-injection-scan.sh --dir agents/ # Scan all files in a directory
#
# Exit codes:
# 0 = clean
# 1 = findings detected
# 2 = usage error
set -euo pipefail
# ─── Patterns ────────────────────────────────────────────────────────────────
# Each pattern is a POSIX extended regex. Keep alphabetized by category.
#
# Left-boundary prefix `(^|[^[:alnum:]])`: several trigger words are also
# suffixes of ordinary English words or camelCase identifiers (fact/impact/
# contract/artifact/interact all end in "act"; retrieval/medieval end in
# "eval"; blueprint/reprint/fingerprint end in "print"; describeFunction/
# wrapFunction end in "Function"; Jordan/Sudan end in "dan"), so an
# unanchored keyword matches as a false-positive substring. `\b` is a GNU
# grep extension and this script must also run under BSD/macOS grep, so the
# boundary is spelled out as `(^|[^[:alnum:]])` instead. This never narrows
# real detections: a genuine attack phrase is always preceded by start-of-
# line, whitespace, or punctuation, never by another alnum character glued
# directly onto the keyword. Only patterns whose leading keyword is provably
# not a real-word suffix are left unanchored (#3175 audit).
PATTERNS=(
# Instruction override
'ignore[[:space:]]+(all[[:space:]]+)?(previous|prior|above|earlier|preceding)[[:space:]]+(instructions|prompts|rules|directives|context)'
'disregard[[:space:]]+(all[[:space:]]+)?(previous|prior|above)[[:space:]]+(instructions|prompts|rules)'
'forget[[:space:]]+(all[[:space:]]+)?(previous|prior|above)[[:space:]]+(instructions|prompts|rules|context)'
'override[[:space:]]+(all[[:space:]]+)?(system|previous|safety)[[:space:]]+(instructions|prompts|rules|checks|filters|guards)'
'override[[:space:]]+(system|safety|security)[[:space:]]'
# Role manipulation
'you[[:space:]]+are[[:space:]]+now[[:space:]]+(a|an|my)[[:space:]]'
'from[[:space:]]+now[[:space:]]+on[[:space:]]+(you|pretend|act|behave)'
'pretend[[:space:]]+(you[[:space:]]+are|to[[:space:]]+be)[[:space:]]'
'(^|[^[:alnum:]])act[[:space:]]+as[[:space:]]+(a|an|if|my)[[:space:]]'
'roleplay[[:space:]]+as[[:space:]]'
'assume[[:space:]]+the[[:space:]]+role[[:space:]]+of[[:space:]]'
# System prompt extraction
'output[[:space:]]+(your|the)[[:space:]]+(system[[:space:]]+)?(prompt|instructions)'
'reveal[[:space:]]+(your|the)[[:space:]]+(system[[:space:]]+)?(prompt|instructions)'
'show[[:space:]]+me[[:space:]]+(your|the)[[:space:]]+(system[[:space:]]+)?(prompt|instructions)'
'(^|[^[:alnum:]])print[[:space:]]+(your|the)[[:space:]]+(system[[:space:]]+)?(prompt|instructions)'
'what[[:space:]]+(is|are)[[:space:]]+(your|the)[[:space:]]+(system[[:space:]]+)?(prompt|instructions)'
'repeat[[:space:]]+(your|the|all)[[:space:]]+(system[[:space:]]+)?(prompt|instructions|rules)'
# Fake message boundaries
'</?system>'
'</?assistant>'
'</?human>'
'\[SYSTEM\]'
'\[/SYSTEM\]'
'\[INST\]'
'\[/INST\]'
'<<SYS>>'
'<</SYS>>'
# Tool call injection / code execution in markdown
#
# The quote-or-apostrophe class below is spelled ["'"'"'"] (a literal `'`
# via bash's close-quote/escape/reopen idiom), not `["\x27]` — `\x27` is a
# GNU-grep-only hex escape; BSD/macOS grep treats it as four literal
# characters (", \, x, 2, 7) and never matches an actual apostrophe, so
# `eval('...')` (single-quoted) silently went undetected on macOS while
# passing on GNU-grep CI runners. Found auditing #3175; fixed here since it
# is the same unanchored/portability defect class as the boundary fix.
'(^|[^[:alnum:]])eval[[:space:]]*\([[:space:]]*["'"'"']'
'exec[[:space:]]*\([[:space:]]*["'"'"']'
'(^|[^[:alnum:]])Function[[:space:]]*\([[:space:]]*["'"'"'].*return'
# Jailbreak / DAN patterns
'do[[:space:]]+anything[[:space:]]+now'
'(^|[^[:alnum:]])DAN[[:space:]]+mode'
'developer[[:space:]]+mode[[:space:]]+(enabled|output|activated)'
'jailbreak'
'bypass[[:space:]]+(safety|content|security)[[:space:]]+(filter|check|rule|guard)'
)
# ─── Allowlist ───────────────────────────────────────────────────────────────
# Files that legitimately discuss injection patterns (security docs, tests, this script)
ALLOWLIST=(
'scripts/prompt-injection-scan.sh'
'scripts/base64-scan.sh'
'scripts/secret-scan.sh'
'tests/security-scan.security.test.cjs'
'tests/security.test.cjs'
'tests/prompt-injection-scan.security.test.cjs'
'tests/verify.test.cjs'
'gsd-core/bin/lib/security.cjs'
'hooks/gsd-prompt-guard.js'
'hooks/gsd-read-injection-scanner.js'
'tests/read-injection-scanner.security.test.cjs'
'tests/read-injection-scanner.property.test.cjs'
'tests/security-prompt-injection.security.test.cjs'
'tests/list-seeds.test.cjs'
'tests/fixtures/adversarial/security/'
'SECURITY.md'
# These files contain intentional injection examples / security-model prose
# and are not attack vectors — they explain/demonstrate injection patterns.
'TEST-EXAMPLES.md'
'explanation/security-model.md'
# The untrusted-input boundary reference quotes injection phrases
# ("ignore previous instructions", "you are now…") as examples agents must
# NOT comply with — it is the defense, not an attack vector.
'references/untrusted-input-boundary.md'
# Security regression tests for input validators — fixtures must contain
# real injection payloads to prove the validator rejects them. See
# DEFECT.PROMPT-INJECTION-SCAN-COLLISION in CONTEXT.md.
'tests/windsurf-conversion.test.cjs'
# RuleTester fixtures for the local/no-unguarded-nonportable-exec ESLint rule
# contain shell-exec command strings (exec("sh -c …"), execFileSync('bash',['-c',…]))
# as test DATA the rule must lint — not attack vectors. ADR-1703 Phase 3 (#1720).
'tests/no-unguarded-nonportable-exec.rule.test.cjs'
# RuleTester fixtures for the local/no-bare-npm-exec ESLint rule contain npm
# exec command strings (execFileSync('npm', ['install'])) as test DATA the rule
# must lint — not attack vectors. ADR-1703 Phase 4 (#1726).
'tests/no-bare-npm-exec.rule.test.cjs'
# #2547 — the Kimi field-shadowing regression proves gsd-prompt-guard still
# SCANS the reconstructed edit[].new content when a model-supplied new_string
# tries to shadow it. The fixture must be a real injection phrase or the test
# asserts nothing: it is the payload the guard is required to catch, carried
# as test DATA. Same class as the read-injection-scanner suites above.
'tests/kimi-payload-field-shadowing.security.test.cjs'
)
is_allowlisted() {
local file="$1"
for allowed in "${ALLOWLIST[@]}"; do
if [[ "$file" == *"$allowed"* ]]; then
return 0
fi
done
return 1
}
# ─── File Collection ─────────────────────────────────────────────────────────
collect_files() {
local mode="$1"
shift
case "$mode" in
--diff)
local base="${1:-origin/main}"
# Get changed files in the diff, filter to scannable extensions
git diff --name-only --diff-filter=ACMR "$base"...HEAD 2>/dev/null \
| grep -E '\.(md|cjs|js|json|yml|yaml|sh)$' || true
;;
--file)
if [[ -f "$1" ]]; then
echo "$1"
else
echo "Error: file not found: $1" >&2
exit 2
fi
;;
--dir)
local dir="$1"
if [[ ! -d "$dir" ]]; then
echo "Error: directory not found: $dir" >&2
exit 2
fi
find "$dir" -type f \( -name '*.md' -o -name '*.cjs' -o -name '*.js' -o -name '*.json' -o -name '*.yml' -o -name '*.yaml' -o -name '*.sh' \) \
! -path '*/node_modules/*' ! -path '*/.git/*' ! -path '*/dist/*' 2>/dev/null || true
;;
--stdin)
cat
;;
*)
echo "Usage: $0 --diff [base] | --file <path> | --dir <path> | --stdin" >&2
exit 2
;;
esac
}
# ─── Scanner ─────────────────────────────────────────────────────────────────
scan_file() {
local file="$1"
local found=0
if is_allowlisted "$file"; then
return 0
fi
for pattern in "${PATTERNS[@]}"; do
# Use grep -iE for case-insensitive extended regex
# -n for line numbers, -c for count mode first to check
local matches
matches=$(grep -inE -e "$pattern" "$file" 2>/dev/null || true)
if [[ -n "$matches" ]]; then
if [[ $found -eq 0 ]]; then
echo "FAIL: $file"
found=1
fi
echo "$matches" | while IFS= read -r line; do
echo " $line"
done
fi
done
return $found
}
# ─── Main ────────────────────────────────────────────────────────────────────
main() {
if [[ $# -eq 0 ]]; then
echo "Usage: $0 --diff [base] | --file <path> | --dir <path>" >&2
exit 2
fi
local mode="$1"
shift
local files
files=$(collect_files "$mode" "$@")
if [[ -z "$files" ]]; then
echo "prompt-injection-scan: no files to scan"
exit 0
fi
local total=0
local failed=0
while IFS= read -r file; do
[[ -z "$file" ]] && continue
total=$((total + 1))
if ! scan_file "$file"; then
failed=$((failed + 1))
fi
done <<< "$files"
echo ""
echo "prompt-injection-scan: scanned $total files, $failed with findings"
if [[ $failed -gt 0 ]]; then
exit 1
fi
exit 0
}
main "$@"