Shellbits Labs
我們的數字,你可以自己重跑。
研究文章引用的每一個實驗都在這裡:程式、執行方式與實際輸出。全部使用合成資料,在暫存目錄執行,不連網,不接觸真實的儲存庫或憑證。
同一個儲存庫,五種匯出方式。各自帶走哪些「已刪除」的內容?
程式在暫存目錄建立一個合成儲存庫,放進四個金絲雀字串:一個曾提交、之後刪除並加入 .gitignore,一個是被忽略的工作檔,一個在已刪除的分支上,一個在已丟棄的 stash 裡。接著用五種方式匯出,檢查哪些金絲雀還原得出來,以及只掃描檔案位元組時看得到哪些。
python3 labs/git-boundary/run.pyGit 2.53.0 · Python 3.14.4 · 輸出記錄於 2026-11-22- 「刪除並忽略」之後,內容仍在可達的歷史裡。任何帶著 refs 的複本都還原得出 A。
- 已刪除的分支與已丟棄的 stash 不會被 clone 帶走,卻還在目錄裡。複製整個目錄,就還原得出 C 與 D。
- 路徑黑名單在
.git的 34 個檔案中沒有比對到任何一個。過濾之後仍還原得出 A、C、D,而位元組掃描一個也看不到。 - 時間只清掉一部分。把提交日期與物件檔的時間都設為 45 天前,再執行預設的
git gc:C 與 D 被回收,物件從 23 個剩下 14 個;A 仍在可達的歷史裡。
| 匯出方式 | 檔案數 | 位元組 | 可還原 | 位元組掃描看得到 |
|---|---|---|---|---|
| 複製工作樹,略過 .git | 6 | 5,790 | B | B |
| git archive HEAD | 5 | 5,756 | 無 | 無 |
| git bundle --all,再 clone | 33 | 36,158 | A | 無 |
| 複製整個目錄 | 40 | 40,741 | ABCD | B |
| 複製整個目錄,套用路徑黑名單 | 38 | 40,688 | ACD | 無 |
限制單一 Git 版本、預設設定、極小的儲存庫。「45 天後」是改寫日期與檔案時間的模擬,沒有真的等 45 天;沒有人執行 gc 的儲存庫,C 與 D 會一直留著。含 .git 的匯出,位元組數會隨執行日期與暫存路徑變動幾個位元組。
run.py 298 行
#!/usr/bin/env python3
"""Lab: what is really inside a repository directory?
Builds a small synthetic repository in a temporary directory, plants four
canary strings in places a developer would call "gone", and then measures
which ways of exporting the project still carry them.
Time is part of the experiment. Git measures reflog expiry from the date of each
reflog entry and the prune grace period from file times. In this script every
reflog entry takes its date from GIT_COMMITTER_DATE, so the script sets both:
* the main run dates everything today ("the developer did this just now");
* a second run dates everything 45 days ago and ages the object files to match,
then lets the same default ``git gc`` decide what is left.
Nothing here touches a real repository, a network, or a real secret.
Usage: python3 run.py [--age-days N] [--keep] [--out results.json]
"""
from __future__ import annotations
import argparse
import fnmatch
import io
import json
import os
import shutil
import subprocess
import sys
import tarfile
import tempfile
import time
from datetime import date, timedelta
from pathlib import Path
CANARIES = {
"A": ("SBX-CANARY-A-7f3a91c2d4", "committed, then deleted and added to .gitignore"),
"B": ("SBX-CANARY-B-0be4c77a19", "ignored working file, never committed"),
"C": ("SBX-CANARY-C-5d20aa8e63", "committed on a branch that was deleted"),
"D": ("SBX-CANARY-D-c41e09b7f5", "stashed, then the stash was dropped"),
}
DENY_PATHS = ["*.env", "*.sql", "*.pem", "*.key", "id_rsa*"] # a typical path filter
AGED_DAYS = 45 # past Git's reflog expiry (30 days) and prune grace period (2 weeks)
ENV = dict(
os.environ,
GIT_CONFIG_GLOBAL=os.devnull, GIT_CONFIG_NOSYSTEM="1",
GIT_AUTHOR_NAME="lab", GIT_AUTHOR_EMAIL="lab@example.invalid",
GIT_COMMITTER_NAME="lab", GIT_COMMITTER_EMAIL="lab@example.invalid",
LC_ALL="C",
)
def set_clock(age_days: int) -> str:
"""Date every commit and reflog entry ``age_days`` before today, at 00:00 local time.
A date fixed in this file would change the result by itself once it was
30 days old, because reflog expiry is measured from it.
"""
day = date.today() - timedelta(days=age_days)
stamp = f"{day.isoformat()}T00:00:00"
ENV["GIT_AUTHOR_DATE"] = ENV["GIT_COMMITTER_DATE"] = stamp
return stamp
def age_objects(repo: Path, age_days: int) -> None:
"""Give the object files a modification time ``age_days`` ago.
The prune grace period (gc.pruneExpire, two weeks) is measured from file
times, not from commit dates.
"""
when = time.time() - age_days * 86400
for p in (repo / ".git" / "objects").rglob("*"):
if p.is_file():
os.utime(p, (when, when))
def git(repo: Path, *args: str, check: bool = True) -> str:
done = subprocess.run(["git", "-C", str(repo), *args], env=ENV, capture_output=True, text=True)
if check and done.returncode:
raise SystemExit(f"git {' '.join(args)} failed: {done.stderr.strip()}")
return done.stdout
def write(path: Path, text: str) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(text, encoding="utf-8")
def build_repo(repo: Path, age_days: int = 0) -> str:
stamp = set_clock(age_days)
repo.mkdir(parents=True)
git(repo, "init", "-q", "-b", "main")
write(repo / "README.md", "# billing-service\n\nSynthetic project for a lab.\n")
write(repo / "src/app.py", "def total(items):\n return sum(i.price for i in items)\n")
write(repo / "docs/design.md", "# Design\n\n" + "Lorem ipsum dolor sit amet. " * 200 + "\n")
write(repo / "config/settings.env", f"API_TOKEN={CANARIES['A'][0]}\nREGION=ap-northeast-1\n")
git(repo, "add", "-A")
git(repo, "commit", "-q", "-m", "initial import")
# "We removed the secret and ignored the file."
git(repo, "rm", "-q", "config/settings.env")
write(repo / ".gitignore", "*.env\n!*.example.env\n")
write(repo / "config/settings.example.env", "API_TOKEN=\nREGION=\n")
git(repo, "add", "-A")
git(repo, "commit", "-q", "-m", "remove settings.env, ignore env files")
# An ignored local file: present on disk, unknown to Git.
write(repo / "config/local.env", f"API_TOKEN={CANARIES['B'][0]}\n")
# A spike branch that is deleted before anyone pushes it.
git(repo, "switch", "-q", "-c", "spike/customer-export")
write(repo / "schema/customers.sql", f"-- export key {CANARIES['C'][0]}\nCREATE TABLE customers (id INT, email TEXT);\n")
git(repo, "add", "-A")
git(repo, "commit", "-q", "-m", "spike: customer export")
git(repo, "switch", "-q", "main")
git(repo, "branch", "-q", "-D", "spike/customer-export")
# A stash that is dropped.
write(repo / "src/app.py", f"DEBUG_TOKEN = '{CANARIES['D'][0]}'\n\ndef total(items):\n return sum(i.price for i in items)\n")
git(repo, "stash", "push", "-q", "-m", "debug token")
git(repo, "stash", "drop", "-q")
# Routine maintenance with default settings (no --prune=now).
if age_days:
age_objects(repo, age_days)
git(repo, "gc", "-q")
return stamp
def tree_stats(root: Path) -> tuple[int, int]:
files = [p for p in root.rglob("*") if p.is_file()]
return len(files), sum(p.stat().st_size for p in files)
def scan_objects(repo: Path) -> set[str]:
"""Canaries recoverable from every object Git can still enumerate."""
found: set[str] = set()
listing = git(repo, "cat-file", "--batch-all-objects", "--batch-check", check=False)
for line in listing.splitlines():
sha, kind, _size = line.split()
if kind != "blob":
continue
data = subprocess.run(["git", "-C", str(repo), "cat-file", "blob", sha], env=ENV, capture_output=True).stdout
for name, (token, _why) in CANARIES.items():
if token.encode() in data:
found.add(name)
return found
def scan_files(root: Path, skip_git: bool = True) -> set[str]:
"""Canaries visible as plain bytes in files (what a string scanner sees)."""
found: set[str] = set()
for p in root.rglob("*"):
if not p.is_file() or (skip_git and ".git" in p.relative_to(root).parts):
continue
data = p.read_bytes()
for name, (token, _why) in CANARIES.items():
if token.encode() in data:
found.add(name)
return found
def raw_hits(root: Path) -> set[str]:
return scan_files(root, skip_git=False)
def measure(label: str, how: str, root: Path, has_git: bool) -> dict:
files, size = tree_stats(root)
plain = scan_files(root)
in_objects = scan_objects(root) if has_git else set()
return {
"export": label,
"how": how,
"files": files,
"bytes": size,
"canaries_in_plain_files": sorted(plain),
"canaries_in_git_objects": sorted(in_objects),
"canaries_recoverable": sorted(plain | in_objects),
"canaries_seen_by_byte_scan": sorted(raw_hits(root)),
}
def repo_stats(repo: Path) -> dict:
return {
"commits_reachable_from_refs": int(git(repo, "rev-list", "--count", "--all").strip() or 0),
"objects_total": len(git(repo, "cat-file", "--batch-all-objects", "--batch-check").splitlines()),
"unreachable_ignoring_reflog": len(git(repo, "fsck", "--unreachable", "--no-reflogs", check=False).splitlines()),
"unreachable_with_reflog": len(git(repo, "fsck", "--unreachable", check=False).splitlines()),
"count_objects": dict(
line.split(": ") for line in git(repo, "count-objects", "-v").strip().splitlines()
),
}
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--age-days", type=int, default=0, help="date the main run this many days ago (default 0)")
ap.add_argument("--keep", action="store_true", help="keep the temporary directory")
ap.add_argument("--out", default=str(Path(__file__).with_name("results.json")))
args = ap.parse_args()
work = Path(tempfile.mkdtemp(prefix="sbx-git-lab-"))
repo = work / "billing-service"
stamp = build_repo(repo, args.age_days)
results = []
# (a) Copy of the working tree without .git
a = work / "a-worktree"
shutil.copytree(repo, a, ignore=shutil.ignore_patterns(".git"))
results.append(measure("worktree-copy", "copy files, skip .git", a, False))
# (b) git archive HEAD
b = work / "b-archive"
b.mkdir()
blob = subprocess.run(["git", "-C", str(repo), "archive", "HEAD"], env=ENV, capture_output=True).stdout
tarfile.open(fileobj=io.BytesIO(blob)).extractall(b, filter="data")
results.append(measure("git-archive", "git archive HEAD", b, False))
# (c) Everything reachable from refs
c = work / "c-clone"
git(repo, "bundle", "create", "-q", str(work / "all.bundle"), "--all")
subprocess.run(["git", "clone", "-q", str(work / "all.bundle"), str(c)], env=ENV, check=True, capture_output=True)
# Note: the clone stores the absolute path of the bundle in its config and reflog,
# so the byte count of this export changes with the temporary directory.
results.append(measure("ref-clone", "git bundle --all, then clone", c, True))
# (d) The whole directory, .git included
d = work / "d-directory"
shutil.copytree(repo, d, symlinks=True)
results.append(measure("directory-snapshot", "copy the whole directory", d, True))
# (e) The whole directory, after a path-based deny list
e = work / "e-filtered"
dropped = []
def deny(directory: str, names: list[str]) -> list[str]:
out = [n for n in names if any(fnmatch.fnmatch(n, pat) for pat in DENY_PATHS)]
dropped.extend(str(Path(directory, n).relative_to(repo)) for n in out)
return out
shutil.copytree(repo, e, symlinks=True, ignore=deny)
row = measure("path-filtered-snapshot", "copy the directory, drop paths matching a deny list", e, True)
row["deny_patterns"] = DENY_PATHS
row["paths_dropped_by_filter"] = sorted(dropped)
results.append(row)
git_paths = [str(p.relative_to(repo)) for p in (repo / ".git").rglob("*") if p.is_file()]
report = {
"lab": "git-boundary",
"git_version": git(repo, "--version").strip(),
"python": sys.version.split()[0],
"canaries": {k: v[1] for k, v in CANARIES.items()},
"run_date": date.today().isoformat(),
"commit_age_days": args.age_days,
"commit_date": stamp,
"repository": {
**repo_stats(repo),
"git_dir_files": len(git_paths),
"git_dir_paths_matching_deny_list": [
p for p in git_paths if any(fnmatch.fnmatch(Path(p).name, pat) for pat in DENY_PATHS)
],
"head_tree": git(repo, "ls-tree", "-r", "--name-only", "HEAD").split(),
},
"exports": results,
}
# The same repository, 45 days later: commit dates and object file times are both
# 45 days old when the same default gc runs. Only the whole directory is measured.
old = work / "aged" / "billing-service"
old_stamp = build_repo(old, AGED_DAYS)
aged = measure("directory-snapshot", "the whole directory, in place", old, True)
report["aged"] = {
"commit_age_days": AGED_DAYS,
"commit_date": old_stamp,
"repository": repo_stats(old),
"canaries_recoverable": aged["canaries_recoverable"],
"canaries_seen_by_byte_scan": aged["canaries_seen_by_byte_scan"],
}
Path(args.out).write_text(json.dumps(report, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
print(f"{report['git_version']} | objects: {report['repository']['objects_total']}"
f" | .git files: {len(git_paths)} | .git paths matching deny list: "
f"{len(report['repository']['git_dir_paths_matching_deny_list'])}")
print(f"{'export':<24}{'files':>6}{'bytes':>9} {'recoverable':<12}{'byte-scan sees':<15}")
for r in results:
print(f"{r['export']:<24}{r['files']:>6}{r['bytes']:>9} "
f"{''.join(r['canaries_recoverable']) or '-':<12}{''.join(r['canaries_seen_by_byte_scan']) or '-':<15}")
print(f"{'same, ' + str(AGED_DAYS) + ' days old':<24}{'':>6}{'':>9} "
f"{''.join(report['aged']['canaries_recoverable']) or '-':<12}"
f"{''.join(report['aged']['canaries_seen_by_byte_scan']) or '-':<15}")
if args.keep:
print("kept:", work)
else:
shutil.rmtree(work, ignore_errors=True)
if __name__ == "__main__":
main()重測全數通過,能把殘餘的成功率壓到多低?
精確的二項式計算,只用標準函式庫,輸出固定。它回答三個問題:n 次全數通過時成功率的上界是多少;要達到目標上界需要幾次;攻擊者重試 k 次後至少成功一次的機率是多少。
python3 labs/retest-bounds/bounds.py只用 Python 標準函式庫 · 輸出記錄於 2026-11-22- 3 次重測全數通過,成功率的 95% 上界是 63.2%。10 次是 25.9%。
- 要把上界壓到 5%,需要連續 59 次未重現。壓到 1% 需要 299 次。
- 真實成功率 3% 的弱點,5 次重測有 85.9% 的機率全數通過。
- 每次成功率 1% 的攻擊,嘗試 100 次後至少成功一次的機率是 63.4%。
| 想證明成功率低於 | 需要的次數(95%) | 需要的次數(99%) |
|---|---|---|
| 20% | 14 | 21 |
| 10% | 29 | 44 |
| 5% | 59 | 90 |
| 2% | 149 | 228 |
| 1% | 299 | 459 |
| 0.5% | 598 | 919 |
| 0.1% | 2,995 | 4,603 |
限制假設每次嘗試互相獨立、成功率固定。真實的代理系統不一定符合這兩點,文章裡有說明。
bounds.py 143 行
#!/usr/bin/env python3
"""Lab: how much does a clean retest prove for a non-deterministic system?
Exact binomial arithmetic only; standard library; deterministic output.
Usage: python3 bounds.py [--out results.json]
"""
from __future__ import annotations
import argparse
import json
import math
import random
from pathlib import Path
def binom_cdf(k: int, n: int, p: float) -> float:
"""P(X <= k) for X ~ Binomial(n, p), summed in log space."""
if p <= 0:
return 1.0
if p >= 1:
return 1.0 if k >= n else 0.0
total = 0.0
for i in range(0, k + 1):
total += math.exp(
math.lgamma(n + 1) - math.lgamma(i + 1) - math.lgamma(n - i + 1)
+ i * math.log(p) + (n - i) * math.log1p(-p)
)
return min(1.0, total)
def upper_bound(x: int, n: int, conf: float = 0.95) -> float:
"""One-sided exact (Clopper-Pearson) upper bound for a success rate."""
if x >= n:
return 1.0
alpha = 1 - conf
if x == 0:
return 1 - alpha ** (1 / n)
lo, hi = x / n, 1.0
for _ in range(80): # bisection on P(X <= x | p) = alpha
mid = (lo + hi) / 2
if binom_cdf(x, n, mid) > alpha:
lo = mid
else:
hi = mid
return hi
def runs_needed(target: float, conf: float = 0.95) -> int:
"""Clean runs needed so the upper bound on the success rate is <= target."""
return math.ceil(math.log(1 - conf) / math.log1p(-target))
def at_least_one(p: float, k: int) -> float:
return 1 - (1 - p) ** k
def coverage(p: float, n: int, conf: float, trials: int, rng: random.Random) -> float:
"""Share of simulated retests whose upper bound is >= the true rate."""
ok = 0
for _ in range(trials):
x = sum(rng.random() < p for _ in range(n))
ok += upper_bound(x, n, conf) >= p
return ok / trials
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--out", default=str(Path(__file__).with_name("results.json")))
args = ap.parse_args()
rng = random.Random(20261122)
clean_runs = [1, 3, 5, 10, 20, 30, 50, 59, 100, 200, 299, 500, 1000]
zero_fail = [
{
"clean_runs": n,
"upper_95": upper_bound(0, n, 0.95),
"upper_99": upper_bound(0, n, 0.99),
"rule_of_three": min(1.0, 3 / n),
}
for n in clean_runs
]
targets = [0.20, 0.10, 0.05, 0.02, 0.01, 0.005, 0.001]
needed = [
{"target_rate": t, "runs_95": runs_needed(t, 0.95), "runs_99": runs_needed(t, 0.99)}
for t in targets
]
rates = [0.001, 0.005, 0.01, 0.05, 0.10]
attempts = [1, 10, 50, 100, 200, 1000]
amplification = [
{"per_attempt_rate": p, **{f"k{k}": at_least_one(p, k) for k in attempts}} for p in rates
]
# A fix that lowers the success rate from 30 % to 3 % is a real improvement,
# and still an open hole. How often does a short retest call each one "not reproduced"?
blind = [
{
"runs": n,
"p_clean_if_rate_30pct": (1 - 0.30) ** n,
"p_clean_if_rate_3pct": (1 - 0.03) ** n,
"p_clean_if_rate_0_5pct": (1 - 0.005) ** n,
}
for n in [1, 3, 5, 10, 20, 50, 100, 300]
]
partial = [
{"successes": x, "runs": n, "observed": x / n, "upper_95": upper_bound(x, n, 0.95)}
for x, n in [(0, 40), (1, 40), (2, 40), (0, 200), (2, 200), (5, 200)]
]
check = [
{"true_rate": p, "runs": n, "trials": 4000, "coverage_95": coverage(p, n, 0.95, 4000, rng)}
for p, n in [(0.01, 59), (0.03, 30), (0.05, 100), (0.10, 20)]
]
report = {
"lab": "retest-bounds",
"definitions": {
"upper_95": "one-sided exact binomial upper bound on the per-attempt success rate, 95 % confidence",
"at_least_one": "probability of one or more successes in k independent attempts",
"coverage_95": "share of simulated retests where the bound is at or above the true rate (seed 20261122)",
},
"zero_failure_bounds": zero_fail,
"clean_runs_needed": needed,
"attacker_attempts": {"attempts": attempts, "rows": amplification},
"short_retest_blindness": blind,
"bounds_with_failures": partial,
"coverage_check": check,
}
Path(args.out).write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8")
print("clean runs -> 95 % upper bound on success rate (rule of three)")
for row in zero_fail:
print(f" {row['clean_runs']:>5} {row['upper_95']:8.4%} ({row['rule_of_three']:.4%})")
print("target rate -> clean runs needed at 95 % / 99 %")
for row in needed:
print(f" {row['target_rate']:7.3%} {row['runs_95']:>5} {row['runs_99']:>5}")
print("per-attempt rate -> P(at least one success) after k attempts", attempts)
for row in amplification:
print(" %6.2f%% " % (row["per_attempt_rate"] * 100) + " ".join(f"{row[f'k{k}']:7.2%}" for k in attempts))
print("runs -> P(retest is clean) if true rate is 30 % / 3 % / 0.5 %")
for row in blind:
print(f" {row['runs']:>4} {row['p_clean_if_rate_30pct']:8.3%} {row['p_clean_if_rate_3pct']:8.3%} {row['p_clean_if_rate_0_5pct']:8.3%}")
print("coverage check:", ", ".join(f"p={c['true_rate']} n={c['runs']}: {c['coverage_95']:.3f}" for c in check))
if __name__ == "__main__":
main()核准綁定的是描述,還是實際的動作?
四個最小的案例。每個案例比較兩種閘門:一種核准動作的描述;另一種核准正規化後的動作,並在執行的當下再驗一次。
python3 labs/approval-binding/demo.py只用 Python 標準函式庫 · POSIX 檔案系統 · 輸出記錄於 2026-11-22- 四個案例中,核准「描述」的閘門全部失效;核准「正規化後的動作」並在執行當下再驗一次的閘門全部守住。
symlink-swap在暫存目錄做真實的檔案操作。其餘三個案例只有判斷邏輯,不執行任何指令。
| 案例 | 核准的內容 | 之後發生的事 | 只綁定描述的閘門 | 綁定動作的閘門 |
|---|---|---|---|---|
symlink-swap | 寫入 notes/todo.md(工作區內) | 核准後,notes/ 被換成指向工作區外的符號連結 | 路徑字串 寫到了工作區外 | 工作區身分,加上以 O_NOFOLLOW 逐層開啟的路徑拒絕寫入 |
name-not-content | MCP 伺服器 build-tools:node tools/build.js | 名稱相同,參數多了 --post scripts/upload-env.js | 伺服器的名稱 沒有詢問就執行 | 正規化內容的 SHA-256 重新詢問 |
prefix-allowlist | 一律允許 git status、git diff、ls | 請求:git status && cat config/local.env | 命令列開頭的字元 沒有詢問就放行 | 解析後的 argv,並拒絕 shell 運算子 先詢問 |
case-fold | 寫入 .agent/settings.json 一律需要確認 | 請求:寫入 .Agent/Settings.JSON | 完全相同的字串 沒有認出受保護的檔案 | 檔案系統實際用來比對的名稱 視為受保護 |
限制這是弱點類別的模型,不是任何產品的利用程式,也不證明任何外部事件。
demo.py 179 行
#!/usr/bin/env python3
"""Lab: what does an approval actually bind?
Four small cases. In each one a "naive" gate approves a description of an
action, and a "bound" gate approves the canonical action itself and checks it
again at the moment of execution.
Case 1 does real file operations inside a temporary directory. Cases 2 to 4
are pure logic: nothing is executed, the gate only decides.
This is a model of a vulnerability class, not an exploit for any product.
Usage: python3 demo.py [--out results.json]
"""
from __future__ import annotations
import argparse
import hashlib
import json
import os
import shlex
import shutil
import tempfile
import unicodedata
from pathlib import Path
# ---------------------------------------------------------------- case 1
def case_symlink_swap(work: Path) -> dict:
"""The prompt shows a path string. The write follows whatever is there later."""
def scene(name: str) -> tuple[Path, Path]:
root = work / name
(root / "workspace" / "notes").mkdir(parents=True)
(root / "outside").mkdir()
return root / "workspace", root / "outside"
def swap(ws: Path, outside: Path) -> None:
# Between approval and execution, a directory becomes a link.
shutil.rmtree(ws / "notes")
os.symlink(outside, ws / "notes")
# naive: approve the string, then open() it
ws, outside = scene("naive")
approved = "notes/todo.md" # what the user saw
swap(ws, outside)
with open(ws / approved, "w") as fh: # follows the link
fh.write("written by the agent\n")
naive_escaped = (outside / "todo.md").exists()
# bound: approve (workspace root identity, relative path), walk without following links
ws, outside = scene("bound")
root_fd = os.open(ws, os.O_RDONLY | os.O_DIRECTORY)
approval = {"root": (os.fstat(root_fd).st_dev, os.fstat(root_fd).st_ino), "rel": ("notes", "todo.md")}
swap(ws, outside)
blocked, reason = False, ""
try:
fd = root_fd
for part in approval["rel"][:-1]:
fd = os.open(part, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=fd)
out = os.open(approval["rel"][-1], os.O_WRONLY | os.O_CREAT | os.O_NOFOLLOW, 0o600, dir_fd=fd)
os.write(out, b"written by the agent\n")
os.close(out)
except OSError as exc:
blocked, reason = True, f"{type(exc).__name__}: {os.strerror(exc.errno)}"
bound_escaped = (outside / "todo.md").exists()
return {
"case": "symlink-swap",
"kind": "real file operations in a temporary directory",
"approved": "write notes/todo.md (inside the workspace)",
"change_after_approval": "notes/ replaced by a symlink to a directory outside the workspace",
"naive": {"binds": "the path string", "wrote_outside_workspace": naive_escaped},
"bound": {"binds": "workspace identity + path walked with O_NOFOLLOW", "wrote_outside_workspace": bound_escaped,
"blocked": blocked, "reason": reason},
}
# ---------------------------------------------------------------- case 2
def case_name_not_content() -> dict:
"""Trust is stored under a name. The thing behind the name changes."""
v1 = {"name": "build-tools", "command": "node", "args": ["tools/build.js"]}
v2 = {"name": "build-tools", "command": "node", "args": ["tools/build.js", "--post", "scripts/upload-env.js"]}
def digest(entry: dict) -> str:
return hashlib.sha256(json.dumps(entry, sort_keys=True, separators=(",", ":")).encode()).hexdigest()
naive_store = {v1["name"]}
bound_store = {v1["name"]: digest(v1)}
return {
"case": "name-not-content",
"kind": "decision logic only",
"approved": f"server '{v1['name']}': {v1['command']} {' '.join(v1['args'])}",
"change_after_approval": f"same name, new args: {' '.join(v2['args'])}",
"naive": {"binds": "the server name", "runs_changed_command_without_prompt": v2["name"] in naive_store},
"bound": {"binds": "SHA-256 of the canonical entry",
"runs_changed_command_without_prompt": bound_store.get(v2["name"]) == digest(v2),
"approved_digest": digest(v1)[:16], "current_digest": digest(v2)[:16]},
}
# ---------------------------------------------------------------- case 3
def case_prefix_allowlist() -> dict:
"""An allowlist checks how a command line starts, not what the shell will run."""
allow = [("git", "status"), ("git", "diff"), ("ls",)]
request = "git status && cat config/local.env"
def naive(cmd: str) -> bool:
return any(cmd.startswith(" ".join(entry)) for entry in allow)
def bound(cmd: str) -> tuple[bool, str]:
lex = shlex.shlex(cmd, posix=True, punctuation_chars=True)
lex.whitespace_split = True
argv = list(lex)
operators = [t for t in argv if t and set(t) <= set(";&|<>()")]
if operators or "$(" in cmd or "`" in cmd:
return False, f"shell operator {operators or ['substitution']}"
ok = any(tuple(argv[: len(entry)]) == entry for entry in allow)
return ok, "argv matches an allowlist entry" if ok else "argv is not on the allowlist"
allowed, why = bound(request)
return {
"case": "prefix-allowlist",
"kind": "decision logic only",
"approved": "always allow: git status, git diff, ls",
"requested": request,
"naive": {"binds": "the first characters of the command line", "allowed_without_prompt": naive(request)},
"bound": {"binds": "the parsed argv, with shell operators rejected", "allowed_without_prompt": allowed, "reason": why},
}
# ---------------------------------------------------------------- case 4
def case_fold() -> dict:
"""A protected-path rule compares strings. The file system compares names."""
protected = [".agent/settings.json"]
request = ".Agent/Settings.JSON" # same file on a case-insensitive volume
def naive(path: str) -> bool:
return path in protected
def bound(path: str) -> bool:
def norm(p: str) -> str:
return unicodedata.normalize("NFC", os.path.normpath(p)).casefold()
return norm(path) in {norm(p) for p in protected}
return {
"case": "case-fold",
"kind": "decision logic only; models a case-insensitive file system",
"approved": f"writes to {protected[0]} always need confirmation",
"requested": f"write {request}",
"naive": {"binds": "an exact string", "treated_as_protected": naive(request)},
"bound": {"binds": "the name as the file system will compare it", "treated_as_protected": bound(request)},
}
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--out", default=str(Path(__file__).with_name("results.json")))
args = ap.parse_args()
work = Path(tempfile.mkdtemp(prefix="sbx-approval-lab-"))
try:
cases = [case_symlink_swap(work), case_name_not_content(), case_prefix_allowlist(), case_fold()]
finally:
shutil.rmtree(work, ignore_errors=True)
Path(args.out).write_text(json.dumps({"lab": "approval-binding", "cases": cases}, indent=2) + "\n", encoding="utf-8")
def verdict(case: dict, gate: str) -> str:
g = case[gate]
if "wrote_outside_workspace" in g:
return "ESCAPED the workspace" if g["wrote_outside_workspace"] else "held (write refused)"
if "runs_changed_command_without_prompt" in g:
return "RAN the changed command" if g["runs_changed_command_without_prompt"] else "held (asks again)"
if "allowed_without_prompt" in g:
return "ALLOWED the chained command" if g["allowed_without_prompt"] else "held (asks first)"
return "held (protected)" if g["treated_as_protected"] else "MISSED the protected file"
for c in cases:
print(f"{c['case']:<18} naive: {verdict(c, 'naive'):<30} bound: {verdict(c, 'bound')}")
if __name__ == "__main__":
main()