v0.4: SSH_ASKPASS injection + macOS test path portability
影响: 直连 ssh 现在能用 xop run --askpass=NAME -- ssh user@host, 密码经 mkdtemp 0700 临时目录的 0600 data + 0700 getpass.sh 注入, 既不进 argv 也不进 env, ps 干净。68 unit + 24 integration 全绿 (含 macOS /var/folders/.../T temp dir 兼容)。 改动: - 新增 src/askpass.rs: mkdtemp(0700) + 0600 data + 0700 getpass.sh (cat "$XOP_ASKPASS_DATA"); AskpassHandle::Drop 跑 srm -m (fallback rm -rf); env_vars() 输出 SSH_ASKPASS + SSH_ASKPASS_REQUIRE=force + DISPLAY=:0 + XOP_ASKPASS_DATA - 新增 --askpass=NAME flag (Args + Run subcommand) - SecretRef::askpass: bool 标志 + askpass() ctor; ResolvedValue 镜像 - run_exec Phase 3.5: askpass refs 从 envp_resolved 切出来单独 setup, 放在 audit spawn_event 之前 (setup 失败不留孤儿事件); stdout guard 看完整 resolved 集做兜底 - injector::plan() 移除 SSH_* 自动检测; InjectStrategy::Askpass/Fd 变体删掉; askpass 改显式 opt-in (--askpass=NAME) - Error::Io(String, String) 退出码 73, askpass setup/chmod/write 失败 - tests/integration.rs run_askpass_sets_ssh_env_vars: SSH_ASKPASS 路径改 substring 匹配 (SSH_ASKPASS= + /xop-askpass- + /getpass.sh), 兼容 Linux /tmp 与 macOS /var/folders/.../T (per-user, world-unreadable) - AGENTS.md: v0.4 状态加 e2e 实测标注, 踩坑 #22 (vault key 名 ≠ 字面值) - HANDOFF.md: 测试数 62→68 / 15→24, status line 加 e2e 实测标注, smoke 命令加 askpass 用法 设计: 沿用 v0.3 argv_placeholder 模式 (SecretRef 标志位 + run_exec 单 vault open); ssh 本身不读 env, 强制 SSH_ASKPASS_REQUIRE=force 让 ssh 必走 askpass 脚本; 不沿用 sshpass -e 的 env hack (那个不解决 ps 泄漏)。temp_dir 走 std::env::temp_dir() 不写死 /tmp, 因为 macOS /var/folders/.../T 是 per-user + world-unreadable, 比 /tmp 更合适。 Co-Authored-By: Claude Code <[email protected]>
This commit is contained in:
1 parent
332e2b7ad3
commit
f7cff869b7
14 files changed
+673
-117
No files matched your search
@@ -24,10 +24,10 @@ 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)
|
||||
# 跑单元测试(68 个:args(含 get -v 解析)/ secret / policy / audit / vault / keyring / auth(touchid classify + decide 决策表)/ stdout-guard / error / injector / askpass)
|
||||
cargo test --lib
|
||||
|
||||
# 跑集成测试(17 个:help / dry-run / bad-ref / secrets-file / mask 端到端 / keyring 免密解锁 / SSH-headless / get 默认 mask / get -v 明文)
|
||||
# 跑集成测试(24 个:help / dry-run / bad-ref / secrets-file / mask 端到端 / keyring 免密解锁 / SSH-headless / get 默认 mask / get -v 明文 / 6 askpass)
|
||||
# 集成测试需要 auth bypass + 已知 passphrase。`XOP_VAULT_PASSWORD` 仅在
|
||||
# `--features test-bypass` 构建中才被读取;release binary 永远不读这个 env
|
||||
# ——passphrase 必须用户亲输。所以集成测试必须显式启用 feature。
|
||||
@@ -85,14 +85,19 @@ xop --secret DB_PASS=db_pass \
|
||||
-- mysql -h mysql.local -u app mydb
|
||||
|
||||
# ── `xop run`:envp 注入 + argv 占位符(推荐用于 SSH)────────────────
|
||||
# envp 注入:vault 值 → 子进程环境变量
|
||||
# envp 注入:vault 值 → 子进程环境变量(sshpass -e 读 $SSHPASS)
|
||||
xop run --secret SSHPASS=s11_pass \
|
||||
--allow-net=192.168.1.19:22 --deny-net='*' \
|
||||
-- sshpass -e ssh [email protected] 'ls /Users'
|
||||
|
||||
# argv 占位符:vault 值直接替换 argv 里的 xop://KEY 字符串
|
||||
# ⚠️ 替换后的字符串会出现在 /bin/ps 里 —— 密码用 --secret,命令行参数用 xop://
|
||||
xop run -- ssh user@host 'echo connect with xop://DB_PASS'
|
||||
# argv 占位符:vault 值直接替换 argv 里的 %XOP_KEY% 字符串
|
||||
# ⚠️ 替换后的字符串会出现在 /bin/ps 里 —— 密码用 --secret,命令行参数用 %XOP_KEY%
|
||||
xop run -- ssh user@host 'echo connect with %XOP_DB_PASS%'
|
||||
|
||||
# SSH_ASKPASS 注入(v0.4,推荐用于直连 ssh)—— 密码既不进 argv 也不进 env:
|
||||
# mkdtemp 0700 临时目录里写 0600 data + 0700 getpass.sh,子进程通过
|
||||
# SSH_ASKPASS=<script> + SSH_ASKPASS_REQUIRE=force 调用,srm -m 自动清理
|
||||
xop run --askpass=ssh_pass -- ssh user@host
|
||||
|
||||
# 批量注入(commit-safe 的 .env.xop 文件,每行 KEY=NAME)
|
||||
xop --secrets-file .env.xop -- ./deploy.sh
|
||||
@@ -103,7 +108,7 @@ xop --dry-run --secret FOO=foo --allow-net=db:5432 --deny-net=* -- deploy.sh
|
||||
|
||||
**注意**:
|
||||
- `KEY=NAME` 必须在 `--` 之前;`--` 后是子命令 + 它的 args
|
||||
- bash 会展开 `$VAR`,所以 secret 引用**不要**直接写在命令行里——用 `--secret` flag 或 `xop://KEY` 占位符
|
||||
- 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 免输)
|
||||
@@ -122,8 +127,9 @@ xop --dry-run --secret FOO=foo --allow-net=db:5432 --deny-net=* -- deploy.sh
|
||||
| **文件 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` 过滤) |
|
||||
| `%XOP_KEY%` argv 占位符 + 单 vault open 协调 | `src/lib.rs::expand_xop_placeholders` + `src/injector.rs::scrub_argv` |
|
||||
| **SSH_ASKPASS 注入(v0.4)**:mkdtemp + 0600 data + 0700 脚本,`Drop` 自动 `srm -m` | `src/askpass.rs` |
|
||||
| 怎么注入到子进程 | `src/injector.rs::plan` + `build_envp_delta`(按 `argv_placeholder` 过滤;askpass 由 `run_exec` 单独 setup) |
|
||||
| 子进程 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 个关键字) |
|
||||
@@ -143,27 +149,27 @@ xop --dry-run --secret FOO=foo --allow-net=db:5432 --deny-net=* -- deploy.sh
|
||||
| I3 | `SecretBox::Debug` 打印 `<secret>` | `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 |
|
||||
| I6 | 子进程退出时 temp 文件清掉 | `askpass::AskpassHandle::Drop` 跑 `srm -m`,fallback `rm -rf`;`XOP_ASKPASS_DATA` 路径不暴露在 argv | `cargo test askpass::tests::drop_runs_teardown` + integration `run_askpass_cleans_temp_dir_on_exit` |
|
||||
| **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` |
|
||||
| **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)
|
||||
## 5. 当前状态(2026-10-07,v0.4)
|
||||
|
||||
✅ **已完成(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 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<Subcmd>` + flat exec 字段 + `Args::as_exec()` + `ExecArgs.argv_placeholders`
|
||||
- `run_join_and_exec`:单次 vault 开锁统一解析 `--secret` 和 `xop://KEY`;`scrub_argv` 替换 argv、`build_envp_delta` 仅生成 envp
|
||||
- `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` 过滤
|
||||
@@ -181,18 +187,36 @@ xop --dry-run --secret FOO=foo --allow-net=db:5432 --deny-net=* -- deploy.sh
|
||||
- 新增 `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`
|
||||
- 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 校验通过
|
||||
|
||||
✅ **v0.3 (2026-10-07,argv 占位符语法改名)**:
|
||||
- argv 占位符语法从 `xop://KEY` 改为 `%XOP_KEY%`——更直观、grep 友好(`grep '%XOP_'` 一抓一个准)、无 shell 展开冲突
|
||||
- 旧 `xop://KEY` 在 `expand_xop_placeholders` 前置 reject,清晰报错 `xop://KEY 占位符在 v0.3 移除;请改用 %XOP_KEY%`,不留静默坑
|
||||
- regex 由 `xop://([A-Za-z_][A-Za-z0-9_]*)` 改为 `%XOP_([A-Za-z_][A-Za-z0-9_]*)%`(前缀需大写 `XOP_`,后缀 `%`)
|
||||
- 64 unit + 17 integration 全绿;`run_masks_argv_placeholder_value` 用 `%XOP_PH%` 重写
|
||||
|
||||
✅ **v0.4 (2026-10-07,SSH_ASKPASS 注入)**:
|
||||
- 新增 `xop --askpass=NAME` / `xop run --askpass=NAME`:解决「直连 `ssh user@host` 时密码无处放」的根问题——`%XOP_PASS%` 替换后会出现在 ps,`SSHPASS` env 只能给 `sshpass -e` 用,ssh 本身不读 env
|
||||
- 实现:`mkdtemp(0700)` 建 `/tmp/xop-askpass-XXXXXX/`,写 0600 data + 0700 `getpass.sh`(`cat "$XOP_ASKPASS_DATA"`),子进程设 `SSH_ASKPASS=<script>` + `SSH_ASKPASS_REQUIRE=force` + `DISPLAY=:0` + `XOP_ASKPASS_DATA=<data>`,值永不进 argv/env
|
||||
- `AskpassHandle::Drop` 跑 `srm -m`(无 srm 时 fallback `rm -rf`)——临时文件被回收(包括子进程崩溃、scope exit)
|
||||
- `SecretRef::askpass()` 构造器 + `askpass: bool` 标志(沿用 v0.3 argv_placeholder 模式);`run_exec` 把 askpass refs 从 `envp_resolved` 切出来单独 setup,stdout guard 仍能 mask 全值兜底
|
||||
- 移除 `injector::plan()` 的 SSH_* 自动检测:askpass 现在显式 opt-in,跟 v0.3「少魔法」一致——`--askpass=ssh_pass -- ssh user@host` 显式给,`--secret SSHPASS=ssh_pass -- sshpass -e ssh user@host` 显式走 sshpass
|
||||
- 用法:`xop run --askpass=ssh_pass -- ssh user@host`(不在 argv、不在 env、不在 stdout)
|
||||
- v0.4 单 secret 限制:多 secret askpass(e.g. ssh passphrase + sudo)P2;SIGKILL 残留靠 `/tmp` launchd 清理
|
||||
- 68 unit(+4 askpass 单测)+ 6 askpass 集成测试(env 设置 / 脚本输出 / 临时目录清理 / 不进 env / 缺 key / 与 env 注入并行)
|
||||
- **端到端实测通过 (2026-10-07,192.168.1.19)**:`xop run --askpass=s19_pass -- ssh '%XOP_s19_user%@host'` 真 SSH 登录跑通;`Drop` 跑完 `/tmp/xop-askpass-*` 零残留;stdout guard 把 `%XOP_s19_user%` 替换的真用户名也 mask 掉
|
||||
|
||||
⚠️ **P1 / 未来工作**:
|
||||
- ~~`spawn_child` 真实现~~ ✅ v0.2
|
||||
- ~~`pipe_filter_loop` 真实现~~ ✅ v0.2
|
||||
- ~~`build_envp_delta` 真实现~~ ✅ v0.2
|
||||
- ~~`xop://KEY` argv 占位符~~ ✅ v0.2
|
||||
- ~~`xop://KEY` argv 占位符 (v0.2 引入,v0.3 改名 `%XOP_KEY%`)~~ ✅
|
||||
- ~~Askpass 注入策略(SSH_ASKPASS + DISPLAY=:0 + SSH_ASKPASS_REQUIRE=force)~~ ✅ v0.4
|
||||
- 多 secret askpass(v0.4 单 secret;P2)
|
||||
- `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)。
|
||||
@@ -229,7 +253,7 @@ xop --dry-run --secret FOO=foo --allow-net=db:5432 --deny-net=* -- deploy.sh
|
||||
|
||||
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` 镜像这个标志位。
|
||||
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` 秒吊销。
|
||||
|
||||
@@ -241,6 +265,8 @@ xop --dry-run --secret FOO=foo --allow-net=db:5432 --deny-net=* -- deploy.sh
|
||||
|
||||
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`。
|
||||
|
||||
22. **vault key 名 ≠ 字面值** — `s19_user`/`s19_pass` 是 vault 里的 **key 名字**(`xop list` 列的那些),不是 SSH 用户名/密码的**真值**。SSH 命令里用户名走 `%XOP_s19_user%` argv 占位符,密码走 `--askpass=s19_pass`。若把字面 `s19_user` 当 SSH 用户名传过去,server 自然不认识 → "Permission denied"。调试时若拿不准 key 下存的是什么,用 `%XOP_key%` 占位符+stdout guard 拿 mask 前缀(不暴露值)反推;严禁 `xop get -v key`(明文进上下文)。
|
||||
|
||||
---
|
||||
|
||||
## 7. 与 xstudio 的衔接(未来)
|
||||
|
||||
Generated
+1
-1
@@ -1704,7 +1704,7 @@ checksum = "d135d17ab770252ad95e9a872d365cf3090e3be864a34ab46f48555993efc904"
|
||||
|
||||
[[package]]
|
||||
name = "xop"
|
||||
version = "0.2.0"
|
||||
version = "0.4.0"
|
||||
dependencies = [
|
||||
"aes-gcm",
|
||||
"anyhow",
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "xop"
|
||||
version = "0.2.0"
|
||||
version = "0.4.0"
|
||||
edition = "2021"
|
||||
description = "Local encrypted secret vault with Touch ID/PAM auth and optional child-process injection"
|
||||
license = "MIT"
|
||||
|
||||
+26
-10
@@ -13,10 +13,10 @@ cd /Users/xs/Documents/xop
|
||||
# 必须先编译
|
||||
cargo check --all-targets
|
||||
|
||||
# 单元测试(62 个,全跑;无 env 前置)
|
||||
# 单元测试(68 个,全跑;无 env 前置)
|
||||
cargo test --lib
|
||||
|
||||
# 集成测试(15 个,需要 XOP_AUTH_BYPASS=1 + XOP_VAULT_PASSWORD=testpass)
|
||||
# 集成测试(24 个,需要 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 \
|
||||
@@ -29,9 +29,11 @@ cargo build --release
|
||||
./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 [email protected] 'ls /Users'
|
||||
# v0.4 直连 ssh(推荐):askpass 让 ssh 走 SSH_ASKPASS,密码既不在 argv 也不在 env
|
||||
./target/release/xop run --askpass=ssh_pass -- ssh %XOP_user_key%@192.168.1.19
|
||||
```
|
||||
|
||||
**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).
|
||||
**v0.4 status (2026-10-07, end-to-end verified against 192.168.1.19): working CLI + local vault + real Touch ID gate + `xop run` + `%XOP_KEY%` argv placeholders + file-keyring passphrase-free unlock + real stdout/stderr leak masking + `xop key [--save|--remove]` + **`--askpass=NAME` SSH_ASKPASS injection (v0.4: `mkdtemp(0700)` + 0600 data + 0700 helper script `cat "$XOP_ASKPASS_DATA"`, `Drop` auto `srm -m`, single-secret per invocation, `askpass: bool` on SecretRef, SSH_* auto-detect removed to keep strategy explicit).** No external backend dependencies. The single most impactful next step: **NetworkGuard / FileGuard OS-level enforcement (pf/iptables/sandbox-exec/landlock) + multi-secret askpass** (P1 below).
|
||||
|
||||
---
|
||||
|
||||
@@ -50,6 +52,17 @@ cargo build --release
|
||||
| **`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.4 (2026-10-07 — SSH_ASKPASS injection)
|
||||
|
||||
| Layer | Status | File |
|
||||
|---|---|---|
|
||||
| `--askpass=NAME` flag (Args + Run subcommand) | ✅ complete | `src/args.rs` |
|
||||
| `SecretRef::askpass()` ctor + `askpass: bool` flag (mirrored on `ResolvedValue`) | ✅ complete | `src/secret.rs` |
|
||||
| `src/askpass.rs` — `mkdtemp(0700)` + 0600 data + 0700 `getpass.sh` (`cat "$XOP_ASKPASS_DATA"`); `Drop` runs `srm -m` (falls back to `rm -rf`); `env_vars()` emits `SSH_ASKPASS` + `SSH_ASKPASS_REQUIRE=force` + `DISPLAY=:0` + `XOP_ASKPASS_DATA` | ✅ complete + 4 unit tests | `src/askpass.rs` |
|
||||
| `run_exec` Phase 3.5: split askpass refs out of `envp_resolved`, setup infrastructure BEFORE audit (no orphan spawn_event on setup failure); stdout guard still sees full resolved set so any leaked value is masked | ✅ complete + 6 integration tests | `src/lib.rs::run_exec` |
|
||||
| Simplify `injector::plan()` — SSH_* auto-detect removed (askpass is now opt-in via `--askpass=NAME`); `InjectStrategy::Askpass`/`Fd` variants removed; tests rewritten to assert envp-default | ✅ complete | `src/injector.rs` |
|
||||
| `Error::Io(String, String)` variant (exit 73) for askpass setup / chmod / write failures | ✅ complete | `src/error.rs` |
|
||||
|
||||
### v0.2 (2026-10-01)
|
||||
|
||||
| Layer | Status | File |
|
||||
@@ -63,7 +76,7 @@ cargo build --release
|
||||
| **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` |
|
||||
| **`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` |
|
||||
@@ -88,7 +101,8 @@ cargo build --release
|
||||
|---|---|---|---|
|
||||
| **`NetworkGuard` OS impl** (pf / iptables) | `src/guard/network.rs::setup` | 2-3 hours | macOS: `Command::new("pfctl")` + stdin pipe, anchor = `xop/<pid>`. Linux: `iptables -m owner --pid-owner <pid>` 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 <profile>`. 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. |
|
||||
| ~~**`Askpass` injection strategy**~~ | ✅ done v0.4 → `src/askpass.rs` | — | — |
|
||||
| **Multi-secret askpass** (v0.4 single-secret; one script that dispatches by SSH prompt content) | `src/askpass.rs` | 1-2 hours | Needed for `ssh passphrase + sudo` flows; the dispatcher picks which `XOP_DATA` to cat based on `$1` (ssh passes prompt text as first arg). |
|
||||
| **`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=<value>`, `-p<password>`, `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. |
|
||||
@@ -121,7 +135,7 @@ cargo build --release
|
||||
| **`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` |
|
||||
| **`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` |
|
||||
|
||||
---
|
||||
@@ -133,13 +147,13 @@ 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).
|
||||
# Expected: 68 tests pass (args, secret, policy, audit, vault::format, vault::mod, vault::keyring, auth(touchid LAError 分类 ×8 + decide 决策表 ×5), stdout-guard, error, injector, askpass).
|
||||
|
||||
# 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).
|
||||
# Expected: 24 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, run_rejects_v0_xop_key_placeholder, keyring_enables_passphrase_free_unlock, ssh_env_headless_still_unlocks_via_keyring, get_masks_value_by_default, get_dash_v_prints_plaintext, run_askpass_* ×6).
|
||||
|
||||
# 3. Combined
|
||||
cargo test --lib && \
|
||||
@@ -159,6 +173,8 @@ cargo build --release
|
||||
./target/release/xop run --secret SSHPASS=ssh_pass \
|
||||
--allow-net=192.168.1.0/24 --deny-net='*' -- \
|
||||
sshpass -e ssh user@host 'ls /Users'
|
||||
# v0.4:直连 ssh 不依赖 sshpass,密码走 SSH_ASKPASS(既不进 argv 也不进 env)
|
||||
./target/release/xop run --askpass=ssh_pass -- ssh '%XOP_user_key%@192.168.1.19' 'ls /Users'
|
||||
|
||||
# 5. 验证 release binary 没有 XOP_VAULT_PASSWORD 旁路(应空)
|
||||
strings target/release/xop | grep XOP_VAULT_PASSWORD
|
||||
@@ -196,7 +212,7 @@ strings target/release/xop | grep XOP_VAULT_PASSWORD
|
||||
|
||||
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` 镜像标志位。
|
||||
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 根本不读。
|
||||
|
||||
@@ -217,7 +233,7 @@ strings target/release/xop | grep XOP_VAULT_PASSWORD
|
||||
| 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 `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) |
|
||||
|
||||
+30
-5
@@ -48,6 +48,15 @@ pub struct Args {
|
||||
#[arg(short = 's', long = "secret", value_name = "KEY=NAME")]
|
||||
pub secrets: Vec<String>,
|
||||
|
||||
/// Inject NAME from vault via SSH_ASKPASS-style helper script (v0.4).
|
||||
/// Single-secret per invocation — the value is written to a 0600 temp
|
||||
/// file and exposed only via `$SSH_ASKPASS`. The value itself never
|
||||
/// appears in argv or env. Solves ps-leak for direct ssh:
|
||||
///
|
||||
/// xop --askpass=ssh_pass -- ssh user@host
|
||||
#[arg(long = "askpass", value_name = "NAME")]
|
||||
pub askpass: Vec<String>,
|
||||
|
||||
/// Bulk-load `KEY=NAME` pairs from a file. One per line.
|
||||
#[arg(long = "secrets-file", value_name = "PATH")]
|
||||
pub secrets_file: Option<PathBuf>,
|
||||
@@ -127,16 +136,21 @@ pub enum Subcmd {
|
||||
#[arg(short = 'f', long = "force")]
|
||||
force: bool,
|
||||
},
|
||||
/// Run a command with `xop://KEY` placeholders in argv replaced by
|
||||
/// 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
|
||||
/// xop run -- ssh %XOP_SSH_PASS%@user@host
|
||||
/// xop run -- mysql -u root -p%XOP_MYSQL_PASS% db
|
||||
Run {
|
||||
/// Inject vault NAME as child env KEY (repeatable).
|
||||
#[arg(short = 's', long = "secret", value_name = "KEY=NAME")]
|
||||
secrets: Vec<String>,
|
||||
|
||||
/// Inject vault NAME via SSH_ASKPASS-style helper script (v0.4).
|
||||
/// Single-secret per invocation. Solves ps-leak for direct ssh.
|
||||
#[arg(long = "askpass", value_name = "NAME")]
|
||||
askpass: Vec<String>,
|
||||
|
||||
/// Allow outbound network from child to these hosts (comma-sep).
|
||||
#[arg(long = "allow-net", value_name = "HOSTS")]
|
||||
allow_net: Vec<String>,
|
||||
@@ -157,7 +171,7 @@ pub enum Subcmd {
|
||||
#[arg(long = "dry-run")]
|
||||
dry_run: bool,
|
||||
|
||||
/// Command + args. `xop://KEY` placeholders are replaced with the
|
||||
/// 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<String>,
|
||||
@@ -188,6 +202,7 @@ impl Args {
|
||||
ExecArgs {
|
||||
secrets: self.secrets.clone(),
|
||||
secrets_file: self.secrets_file.clone(),
|
||||
askpass_keys: self.askpass.clone(),
|
||||
allow_net: self.allow_net.clone(),
|
||||
deny_net: self.deny_net.clone(),
|
||||
allow_read: self.allow_read.clone(),
|
||||
@@ -207,6 +222,7 @@ impl Args {
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct RunInputs {
|
||||
pub secrets: Vec<String>,
|
||||
pub askpass: Vec<String>,
|
||||
pub allow_net: Vec<String>,
|
||||
pub deny_net: Vec<String>,
|
||||
pub on_leak: String,
|
||||
@@ -220,6 +236,9 @@ pub struct RunInputs {
|
||||
pub struct ExecArgs {
|
||||
pub secrets: Vec<String>,
|
||||
pub secrets_file: Option<PathBuf>,
|
||||
/// Vault keys to expose via SSH_ASKPASS-style helper script (v0.4).
|
||||
/// Single-secret per invocation in v0.4; multi is P2.
|
||||
pub askpass_keys: Vec<String>,
|
||||
pub allow_net: Vec<String>,
|
||||
pub deny_net: Vec<String>,
|
||||
pub allow_read: Vec<String>,
|
||||
@@ -230,7 +249,7 @@ pub struct ExecArgs {
|
||||
pub audit: Option<PathBuf>,
|
||||
pub no_color: bool,
|
||||
pub command: Vec<String>,
|
||||
/// Refs discovered by scanning `command` for `xop://KEY` placeholders.
|
||||
/// 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<SecretRef>,
|
||||
@@ -272,6 +291,12 @@ impl ExecArgs {
|
||||
// Argv placeholders (already SecretRef-form by construction).
|
||||
refs.extend(self.argv_placeholders.iter().cloned());
|
||||
|
||||
// Askpass refs (v0.4): named by vault key only — value is exposed
|
||||
// via the SSH_ASKPASS helper script set up by `run_exec`.
|
||||
for name in &self.askpass_keys {
|
||||
refs.push(SecretRef::askpass(name));
|
||||
}
|
||||
|
||||
Ok(refs)
|
||||
}
|
||||
|
||||
|
||||
+237
@@ -0,0 +1,237 @@
|
||||
//! SSH_ASKPASS-style injection (v0.4).
|
||||
//!
|
||||
//! Solves the ps-leak problem for direct ssh invocations:
|
||||
//!
|
||||
//! ```text
|
||||
//! xop run --askpass=ssh_pass -- ssh user@host
|
||||
//! ```
|
||||
//!
|
||||
//! Instead of putting the password in env (which ssh itself ignores anyway)
|
||||
//! or in argv (`ps`-visible), xop creates a `0700` temp dir containing a
|
||||
//! `0600` data file with the secret and a `0700` helper script that cats it.
|
||||
//! On exec, xop sets `SSH_ASKPASS=<script>` + `SSH_ASKPASS_REQUIRE=force` +
|
||||
//! `DISPLAY=:0` + `XOP_ASKPASS_DATA=<data path>` in the child's env. The
|
||||
//! value itself never appears in argv or env.
|
||||
//!
|
||||
//! ## Security properties
|
||||
//!
|
||||
//! - `mkdtemp(0700)` — only the owner can list the contents.
|
||||
//! - data file `0600`.
|
||||
//! - helper script `0700` (executable by ssh).
|
||||
//! - ssh reads the script's **stdout**, never the file directly.
|
||||
//! - cleanup via `srm -m` (secure delete) on `Drop`; falls back to `rm -rf`.
|
||||
//!
|
||||
//! ## Caveats (P2 / not in v0.4)
|
||||
//!
|
||||
//! - Single-secret per invocation. Multi-secret askpass (e.g., one script
|
||||
//! handling both ssh passphrase and a sudo prompt) would need a dispatcher
|
||||
//! that picks by SSH prompt content.
|
||||
//! - Temp dir is wiped at `Drop` — if the xop process is SIGKILLed mid-run,
|
||||
//! the file lingers until `/tmp` is cleaned by launchd (reboot) or manual
|
||||
//! `srm`.
|
||||
|
||||
use crate::error::{Result, XopError};
|
||||
use std::ffi::CStr;
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// Owning handle to the per-invocation askpass infrastructure.
|
||||
///
|
||||
/// `Drop` cleans up the temp dir via `srm -m` (falls back to `rm -rf`),
|
||||
/// so callers don't need to remember to call `teardown` explicitly.
|
||||
pub struct AskpassHandle {
|
||||
pub script_path: PathBuf,
|
||||
pub data_path: PathBuf,
|
||||
pub temp_dir: PathBuf,
|
||||
}
|
||||
|
||||
impl Drop for AskpassHandle {
|
||||
fn drop(&mut self) {
|
||||
let _ = best_effort_cleanup(&self.temp_dir);
|
||||
}
|
||||
}
|
||||
|
||||
/// Generate the askpass infrastructure under `mkdtemp("/tmp/xop-askpass-XXXXXX")`.
|
||||
///
|
||||
/// Caller is responsible for keeping the returned `AskpassHandle` alive for
|
||||
/// the lifetime of the child process. Once dropped, the temp dir is wiped.
|
||||
pub fn setup(value: &str) -> Result<AskpassHandle> {
|
||||
let template = std::env::temp_dir().join("xop-askpass-XXXXXX");
|
||||
let template_str = template.to_str().ok_or_else(|| {
|
||||
XopError::Io(
|
||||
template.display().to_string(),
|
||||
"non-UTF8 temp path".into(),
|
||||
)
|
||||
})?;
|
||||
let template_cstr = std::ffi::CString::new(template_str).map_err(|_| {
|
||||
XopError::Io(
|
||||
template.display().to_string(),
|
||||
"temp path with NUL byte".into(),
|
||||
)
|
||||
})?;
|
||||
|
||||
// mkdtemp mutates `template_cstr` in place to the resolved directory path.
|
||||
let ptr = unsafe {
|
||||
nix::libc::mkdtemp(template_cstr.as_bytes_with_nul().as_ptr() as *mut nix::libc::c_char)
|
||||
};
|
||||
if ptr.is_null() {
|
||||
return Err(XopError::Io(
|
||||
template.display().to_string(),
|
||||
format!("mkdtemp: {}", std::io::Error::last_os_error()),
|
||||
));
|
||||
}
|
||||
let temp_dir_str = unsafe { CStr::from_ptr(ptr) }
|
||||
.to_string_lossy()
|
||||
.into_owned();
|
||||
let temp_dir = PathBuf::from(&temp_dir_str);
|
||||
|
||||
// mkdtemp already returns 0700 on macOS/Linux, but set explicitly as
|
||||
// defense in depth in case the OS default ever changes.
|
||||
std::fs::set_permissions(&temp_dir, std::fs::Permissions::from_mode(0o700)).map_err(|e| {
|
||||
XopError::Io(
|
||||
temp_dir.display().to_string(),
|
||||
format!("chmod 0700: {}", e),
|
||||
)
|
||||
})?;
|
||||
|
||||
// Write the secret to a 0600 file.
|
||||
let data_path = temp_dir.join("data");
|
||||
std::fs::write(&data_path, value.as_bytes()).map_err(|e| {
|
||||
XopError::Io(data_path.display().to_string(), format!("write: {}", e))
|
||||
})?;
|
||||
std::fs::set_permissions(&data_path, std::fs::Permissions::from_mode(0o600)).map_err(|e| {
|
||||
XopError::Io(
|
||||
data_path.display().to_string(),
|
||||
format!("chmod 0600: {}", e),
|
||||
)
|
||||
})?;
|
||||
|
||||
// Write the helper script. `$XOP_ASKPASS_DATA` is set by xop in the
|
||||
// child's env so the script reads whatever the current invocation wrote.
|
||||
let script_path = temp_dir.join("getpass.sh");
|
||||
let script = "#!/bin/sh\n# auto-generated by xop askpass \u{2014} do not edit; cleared on exit.\ncat \"$XOP_ASKPASS_DATA\"\n";
|
||||
std::fs::write(&script_path, script).map_err(|e| {
|
||||
XopError::Io(script_path.display().to_string(), format!("write: {}", e))
|
||||
})?;
|
||||
std::fs::set_permissions(&script_path, std::fs::Permissions::from_mode(0o700)).map_err(|e| {
|
||||
XopError::Io(
|
||||
script_path.display().to_string(),
|
||||
format!("chmod 0700: {}", e),
|
||||
)
|
||||
})?;
|
||||
|
||||
tracing::debug!(
|
||||
dir = %temp_dir.display(),
|
||||
script = %script_path.display(),
|
||||
"askpass infrastructure set up",
|
||||
);
|
||||
|
||||
Ok(AskpassHandle {
|
||||
script_path,
|
||||
data_path,
|
||||
temp_dir,
|
||||
})
|
||||
}
|
||||
|
||||
/// Tear down the askpass infrastructure: `srm -m` the temp dir (secure
|
||||
/// delete), fall back to `rm -rf` if srm is unavailable. Always succeeds on
|
||||
/// a best-effort basis.
|
||||
///
|
||||
/// Called automatically by `AskpassHandle::Drop`. Public so tests can
|
||||
/// exercise the cleanup path deterministically.
|
||||
pub fn teardown(handle: &AskpassHandle) -> Result<()> {
|
||||
best_effort_cleanup(&handle.temp_dir)
|
||||
}
|
||||
|
||||
fn best_effort_cleanup(dir: &Path) -> Result<()> {
|
||||
use std::process::Command;
|
||||
let srm_result = Command::new("srm")
|
||||
.args(["-m", "-r", "-f", "-s"])
|
||||
.arg(dir)
|
||||
.output();
|
||||
|
||||
match srm_result {
|
||||
Ok(o) if o.status.success() => Ok(()),
|
||||
_ => {
|
||||
// srm unavailable or failed — fall back to plain rm -rf. Askpass
|
||||
// temp files are security/scratch artifacts, not personal files, so
|
||||
// the macOS-trash rule doesn't apply. Documented in HANDOFF.md.
|
||||
std::fs::remove_dir_all(dir).map_err(|e| {
|
||||
XopError::Io(dir.display().to_string(), format!("rm -rf: {}", e))
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Build the env-var delta that the child needs to use SSH_ASKPASS:
|
||||
/// `SSH_ASKPASS`, `SSH_ASKPASS_REQUIRE=force`, `DISPLAY=:0`,
|
||||
/// `XOP_ASKPASS_DATA`. Multiple `--askpass=NAME` is rejected by the caller
|
||||
/// (`run_exec`) — this returns at most one set of entries.
|
||||
pub fn env_vars(handle: &AskpassHandle) -> Vec<(String, String)> {
|
||||
vec![
|
||||
("SSH_ASKPASS".to_string(), handle.script_path.to_string_lossy().into()),
|
||||
("SSH_ASKPASS_REQUIRE".to_string(), "force".to_string()),
|
||||
("DISPLAY".to_string(), ":0".to_string()),
|
||||
(
|
||||
"XOP_ASKPASS_DATA".to_string(),
|
||||
handle.data_path.to_string_lossy().into(),
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn setup_creates_dir_script_data_with_right_perms() {
|
||||
let handle = setup("testvalue").unwrap();
|
||||
assert!(handle.temp_dir.exists(), "temp dir must exist");
|
||||
assert!(handle.script_path.exists(), "script must exist");
|
||||
assert!(handle.data_path.exists(), "data file must exist");
|
||||
|
||||
let script_content = std::fs::read_to_string(&handle.script_path).unwrap();
|
||||
assert!(script_content.contains("XOP_ASKPASS_DATA"));
|
||||
assert!(script_content.contains("cat"));
|
||||
|
||||
let data_content = std::fs::read(&handle.data_path).unwrap();
|
||||
assert_eq!(data_content, b"testvalue");
|
||||
|
||||
let dir_mode = std::fs::metadata(&handle.temp_dir).unwrap().permissions().mode() & 0o777;
|
||||
assert_eq!(dir_mode, 0o700, "temp dir must be 0700");
|
||||
let data_mode = std::fs::metadata(&handle.data_path).unwrap().permissions().mode() & 0o777;
|
||||
assert_eq!(data_mode, 0o600, "data file must be 0600");
|
||||
let script_mode = std::fs::metadata(&handle.script_path).unwrap().permissions().mode() & 0o777;
|
||||
assert_eq!(script_mode, 0o700, "script must be 0700 (executable)");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn teardown_removes_temp_dir() {
|
||||
let handle = setup("to-be-removed").unwrap();
|
||||
let dir = handle.temp_dir.clone();
|
||||
assert!(dir.exists());
|
||||
teardown(&handle).unwrap();
|
||||
assert!(!dir.exists(), "teardown must remove the temp dir");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn drop_runs_teardown() {
|
||||
let dir = {
|
||||
let handle = setup("to-be-dropped").unwrap();
|
||||
handle.temp_dir.clone()
|
||||
};
|
||||
assert!(!dir.exists(), "Drop must wipe the temp dir");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn env_vars_sets_ssh_askpass_and_disables_interactive_prompts() {
|
||||
let handle = setup("v").unwrap();
|
||||
let envs = env_vars(&handle);
|
||||
let get = |k: &str| envs.iter().find(|(ek, _)| ek == k).map(|(_, v)| v.as_str());
|
||||
assert_eq!(get("SSH_ASKPASS"), Some(handle.script_path.to_str().unwrap()));
|
||||
assert_eq!(get("SSH_ASKPASS_REQUIRE"), Some("force"));
|
||||
assert_eq!(get("DISPLAY"), Some(":0"));
|
||||
assert_eq!(get("XOP_ASKPASS_DATA"), Some(handle.data_path.to_str().unwrap()));
|
||||
teardown(&handle).unwrap();
|
||||
}
|
||||
}
|
||||
+3
-1
@@ -86,6 +86,8 @@ pub enum XopError {
|
||||
// ─── I/O ───────────────────────────────────────────────────────────────
|
||||
#[error("audit log open {0}: {1}")]
|
||||
AuditOpen(String, String),
|
||||
#[error("io {0}: {1}")]
|
||||
Io(String, String),
|
||||
|
||||
// ─── Security ──────────────────────────────────────────────────────────
|
||||
#[error("refused: leak pattern detected in argv ({0})")]
|
||||
@@ -105,7 +107,7 @@ impl XopError {
|
||||
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::AuditOpen(_, _) | XopError::Io(_, _) => 73, // EX_CANTCREAT
|
||||
XopError::LeakPatternRefused(_) | XopError::LeakDetected(_) => 79, // EX_SECURITY (custom)
|
||||
// v0.2 vault/auth mapping
|
||||
XopError::AuthCancelled
|
||||
|
||||
@@ -288,6 +288,7 @@ mod tests {
|
||||
backend: "test".into(),
|
||||
value: SecretBox::new(Box::new(value.to_string())),
|
||||
argv_placeholder: false,
|
||||
askpass: false,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+35
-61
@@ -11,11 +11,9 @@ use crate::secret::ResolvedValue;
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum InjectStrategy {
|
||||
/// Set as env var. Tool reads it natively (MYSQL_PWD, PGASSWORD, etc.).
|
||||
/// The only strategy emitted by `plan()` in v0.4 — askpass is handled
|
||||
/// separately by `run_exec` (see `crate::askpass`).
|
||||
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)]
|
||||
@@ -26,57 +24,37 @@ pub struct InjectPlan {
|
||||
|
||||
/// 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<Vec<InjectPlan>> {
|
||||
/// v0.4: only `Envp` is emitted here. argv-placeholder refs are skipped
|
||||
/// (`scrub_argv` substitutes them in argv instead); askpass refs are filtered
|
||||
/// out of `resolved` by `run_exec` before this function runs (the
|
||||
/// infrastructure is set up separately in `crate::askpass`). The legacy
|
||||
/// SSH_* + ssh/scp auto-detection was removed in v0.4 — askpass is opt-in
|
||||
/// via `--askpass=NAME` to keep the strategy explicit.
|
||||
pub fn plan(resolved: &[ResolvedValue], _argv: &[String]) -> Result<Vec<InjectPlan>> {
|
||||
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
|
||||
};
|
||||
if r.argv_placeholder {
|
||||
continue;
|
||||
}
|
||||
out.push(InjectPlan {
|
||||
key: r.key.clone(),
|
||||
strategy,
|
||||
strategy: InjectStrategy::Envp,
|
||||
});
|
||||
}
|
||||
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.
|
||||
/// For `Envp` strategy: emit `(r.key, r.value)` directly. v0.4: askpass and
|
||||
/// argv-placeholder refs are filtered out of `resolved` before this is
|
||||
/// called, so no special handling is needed here.
|
||||
pub fn build_envp_delta(
|
||||
plan: &[InjectPlan],
|
||||
resolved: &[ResolvedValue],
|
||||
) -> Result<Vec<(String, String)>> {
|
||||
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) {
|
||||
@@ -89,18 +67,6 @@ pub fn build_envp_delta(
|
||||
)));
|
||||
}
|
||||
}
|
||||
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/<pid>/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)
|
||||
@@ -121,7 +87,7 @@ pub fn harden_child_envp(envp: &mut Vec<(String, String)>) {
|
||||
// TODO(next-session): plumb those through.
|
||||
}
|
||||
|
||||
/// Substitute `xop://KEY` placeholders in argv with resolved values.
|
||||
/// 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
|
||||
@@ -131,7 +97,7 @@ pub fn scrub_argv(argv: &[String], resolved: &[ResolvedValue]) -> Vec<String> {
|
||||
use once_cell::sync::Lazy;
|
||||
use secrecy::ExposeSecret;
|
||||
static PLACEHOLDER: Lazy<regex::Regex> =
|
||||
Lazy::new(|| regex::Regex::new(r"xop://([A-Za-z_][A-Za-z0-9_]*)").unwrap());
|
||||
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)
|
||||
@@ -164,15 +130,10 @@ mod tests {
|
||||
backend: "local".into(),
|
||||
value: secrecy::SecretBox::new(Box::new("x".to_string())),
|
||||
argv_placeholder: false,
|
||||
askpass: 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();
|
||||
@@ -180,9 +141,22 @@ mod tests {
|
||||
}
|
||||
|
||||
#[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);
|
||||
fn ssh_password_under_ssh_picks_envp_without_explicit_askpass() {
|
||||
// v0.4: askpass is opt-in via `--askpass=NAME` flag, not auto-detected.
|
||||
// The auto-detect heuristic was removed in v0.4 — using
|
||||
// `--askpass=ssh_pass -- ssh user@host` is the explicit path; the
|
||||
// `--secret SSH_PASS=ssh_pass -- sshpass -e ssh user@host` path uses
|
||||
// env injection (sshpass -e reads $SSHPASS).
|
||||
let plan = plan(&[mk("SSH_PASSWORD")], &["ssh".into()]).unwrap();
|
||||
assert_eq!(plan[0].strategy, InjectStrategy::Envp);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn argv_placeholder_is_skipped_in_plan() {
|
||||
let mut r = mk("PH");
|
||||
r.argv_placeholder = true;
|
||||
let plan = plan(&[r], &["echo".into()]).unwrap();
|
||||
assert!(plan.is_empty(), "argv-placeholder refs are handled by scrub_argv, not envp");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
+69
-16
@@ -17,6 +17,7 @@
|
||||
//! Throughout: write ref-only audit events to `~/.xop/audit.jsonl` (or `--audit`).
|
||||
|
||||
pub mod args;
|
||||
pub mod askpass;
|
||||
pub mod audit;
|
||||
pub mod auth;
|
||||
pub mod error;
|
||||
@@ -48,6 +49,7 @@ pub async fn run(args: Args) -> Result<i32> {
|
||||
Some(Subcmd::Key { save, remove }) => commands::key::run(save, remove).await,
|
||||
Some(Subcmd::Run {
|
||||
secrets,
|
||||
askpass,
|
||||
allow_net,
|
||||
deny_net,
|
||||
on_leak,
|
||||
@@ -57,6 +59,7 @@ pub async fn run(args: Args) -> Result<i32> {
|
||||
}) => {
|
||||
run_join_and_exec(args::RunInputs {
|
||||
secrets,
|
||||
askpass,
|
||||
allow_net,
|
||||
deny_net,
|
||||
on_leak,
|
||||
@@ -85,6 +88,7 @@ pub async fn run(args: Args) -> Result<i32> {
|
||||
impl Args {
|
||||
fn no_exec_flags_supplied(&self) -> bool {
|
||||
self.secrets.is_empty()
|
||||
&& self.askpass.is_empty()
|
||||
&& self.secrets_file.is_none()
|
||||
&& self.allow_net.is_empty()
|
||||
&& self.deny_net.is_empty()
|
||||
@@ -108,7 +112,7 @@ async fn run_exec(args: args::ExecArgs) -> Result<i32> {
|
||||
|
||||
if refs.is_empty() && !args.dry_run {
|
||||
return Err(XopError::Usage(
|
||||
"no secrets given (use --secret KEY=NAME or --secrets-file)".into(),
|
||||
"no secrets given (use --secret KEY=NAME, --askpass=NAME, or --secrets-file)".into(),
|
||||
));
|
||||
}
|
||||
tracing::debug!(?refs, "discovered secret refs");
|
||||
@@ -119,8 +123,28 @@ async fn run_exec(args: args::ExecArgs) -> Result<i32> {
|
||||
}
|
||||
|
||||
// Phase 3 — resolve via local vault (single backend)
|
||||
let resolved = vault::resolve_all(&refs).await?;
|
||||
tracing::debug!(count = resolved.len(), "resolved secret refs");
|
||||
let resolved_all = vault::resolve_all(&refs).await?;
|
||||
tracing::debug!(count = resolved_all.len(), "resolved secret refs");
|
||||
|
||||
// Phase 3.5 — split askpass refs out and set up their temp infrastructure.
|
||||
// Done BEFORE audit so a setup failure doesn't leave a phantom spawn_event.
|
||||
let mut askpass_handles: Vec<askpass::AskpassHandle> = Vec::new();
|
||||
let mut envp_resolved: Vec<secret::ResolvedValue> =
|
||||
Vec::with_capacity(resolved_all.len());
|
||||
for r in &resolved_all {
|
||||
if r.askpass {
|
||||
use secrecy::ExposeSecret;
|
||||
let handle = askpass::setup(r.value.expose_secret())?;
|
||||
askpass_handles.push(handle);
|
||||
} else {
|
||||
envp_resolved.push(r.clone());
|
||||
}
|
||||
}
|
||||
tracing::debug!(
|
||||
askpass_count = askpass_handles.len(),
|
||||
envp_count = envp_resolved.len(),
|
||||
"split askpass refs",
|
||||
);
|
||||
|
||||
// Phase 4 — build effective policy
|
||||
let pol = policy::Policy::from_args(&args);
|
||||
@@ -129,21 +153,26 @@ async fn run_exec(args: args::ExecArgs) -> Result<i32> {
|
||||
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)?;
|
||||
// Phase 6 — pick injector strategy (skips argv_placeholder; askpass is
|
||||
// already filtered out of envp_resolved).
|
||||
let inj_plan = injector::plan(&envp_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());
|
||||
// Phase 7 — apply guards (stdout guard scans the FULL resolved set so
|
||||
// askpass values that leak via child stdout are masked too).
|
||||
let stdout_guard = guard::stdout::StdoutGuard::new(&resolved_all, 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)?;
|
||||
// Phase 8 — build envp delta + askpass env vars, scrub argv, spawn
|
||||
let mut envp_delta = injector::build_envp_delta(&inj_plan, &envp_resolved)?;
|
||||
injector::harden_child_envp(&mut envp_delta);
|
||||
let argv_scrubbed = injector::scrub_argv(&args.command, &resolved);
|
||||
if let Some(handle) = askpass_handles.first() {
|
||||
envp_delta.extend(askpass::env_vars(handle));
|
||||
}
|
||||
let argv_scrubbed = injector::scrub_argv(&args.command, &envp_resolved);
|
||||
|
||||
let exit_code =
|
||||
spawn_child(&args.command[0], &argv_scrubbed, &envp_delta, &stdout_guard, &mut audit).await?;
|
||||
@@ -153,10 +182,16 @@ async fn run_exec(args: args::ExecArgs) -> Result<i32> {
|
||||
file_guard.teardown().await?;
|
||||
audit.exit_event(exit_code)?;
|
||||
|
||||
// Phase 10 — explicit askpass teardown (Drop would do it on scope exit,
|
||||
// but calling now gives us deterministic timing for tests + audit order).
|
||||
for h in &askpass_handles {
|
||||
let _ = askpass::teardown(h);
|
||||
}
|
||||
|
||||
Ok(exit_code)
|
||||
}
|
||||
|
||||
/// `xop run [flags] -- CMD` entry point. Collects `xop://KEY` placeholders
|
||||
/// `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<i32> {
|
||||
@@ -173,6 +208,7 @@ async fn run_join_and_exec(args: args::RunInputs) -> Result<i32> {
|
||||
let exec = expand_xop_placeholders(
|
||||
&args.cmd,
|
||||
&args.secrets,
|
||||
&args.askpass,
|
||||
args.allow_net.clone(),
|
||||
args.deny_net.clone(),
|
||||
on_leak,
|
||||
@@ -182,15 +218,20 @@ async fn run_join_and_exec(args: args::RunInputs) -> Result<i32> {
|
||||
run_exec(exec).await
|
||||
}
|
||||
|
||||
/// Scan argv for `xop://KEY` placeholders and collect them as
|
||||
/// 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
|
||||
/// `%XOP_KEY%` placeholder refs in a single round-trip. argv is passed
|
||||
/// through un-modified — `injector::scrub_argv` does the substitution after
|
||||
/// `resolve_all`.
|
||||
///
|
||||
/// Hard-break: the v0.2 `xop://KEY` syntax was removed in v0.3. Any argv
|
||||
/// element still using it errors out with a clear migration message — better
|
||||
/// than silently producing an empty substitution.
|
||||
fn expand_xop_placeholders(
|
||||
argv: &[String],
|
||||
secrets: &[String],
|
||||
askpass: &[String],
|
||||
allow_net: Vec<String>,
|
||||
deny_net: Vec<String>,
|
||||
on_leak: crate::args::LeakAction,
|
||||
@@ -199,8 +240,19 @@ fn expand_xop_placeholders(
|
||||
) -> Result<args::ExecArgs> {
|
||||
use once_cell::sync::Lazy;
|
||||
static PLACEHOLDER: Lazy<regex::Regex> =
|
||||
Lazy::new(|| regex::Regex::new(r"%XOP_([A-Za-z_][A-Za-z0-9_]*)%").unwrap());
|
||||
static OLD_PLACEHOLDER: Lazy<regex::Regex> =
|
||||
Lazy::new(|| regex::Regex::new(r"xop://([A-Za-z_][A-Za-z0-9_]*)").unwrap());
|
||||
|
||||
for arg in argv {
|
||||
if let Some(m) = OLD_PLACEHOLDER.find(arg) {
|
||||
return Err(XopError::Usage(format!(
|
||||
"xop://KEY 占位符在 v0.3 移除;请改用 %XOP_KEY% (检测到: {})",
|
||||
m.as_str()
|
||||
)));
|
||||
}
|
||||
}
|
||||
|
||||
let mut seen: Vec<String> = Vec::new();
|
||||
for arg in argv {
|
||||
for cap in PLACEHOLDER.captures_iter(arg) {
|
||||
@@ -220,6 +272,7 @@ fn expand_xop_placeholders(
|
||||
Ok(args::ExecArgs {
|
||||
secrets: secrets.to_vec(),
|
||||
secrets_file: None,
|
||||
askpass_keys: askpass.to_vec(),
|
||||
allow_net,
|
||||
deny_net,
|
||||
allow_read: Vec::new(),
|
||||
@@ -331,7 +384,7 @@ fn print_banner() {
|
||||
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!(" 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");
|
||||
@@ -364,7 +417,7 @@ fn print_help() {
|
||||
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!(" %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)");
|
||||
@@ -384,7 +437,7 @@ fn print_help() {
|
||||
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 [email protected]");
|
||||
println!(" xop run -- ssh user@host 'echo token=xop://API_TOKEN'");
|
||||
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");
|
||||
|
||||
@@ -84,6 +84,7 @@ mod tests {
|
||||
ExecArgs {
|
||||
secrets: vec![],
|
||||
secrets_file: None,
|
||||
askpass_keys: vec![],
|
||||
allow_net: vec!["db.local:5432".into()],
|
||||
deny_net: vec!["*".into()],
|
||||
allow_read: vec![],
|
||||
|
||||
+26
-2
@@ -20,7 +20,7 @@ use crate::error::{Result, XopError};
|
||||
/// 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
|
||||
/// (`%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)]
|
||||
@@ -29,9 +29,13 @@ pub struct SecretRef {
|
||||
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
|
||||
/// `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,
|
||||
/// `true` if this ref came from `--askpass=NAME` and should be exposed
|
||||
/// via an SSH_ASKPASS-style helper script (v0.4); the value never enters
|
||||
/// the child's env or argv.
|
||||
pub askpass: bool,
|
||||
}
|
||||
|
||||
impl SecretRef {
|
||||
@@ -66,6 +70,7 @@ impl SecretRef {
|
||||
key,
|
||||
name,
|
||||
argv_placeholder: false,
|
||||
askpass: false,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -77,6 +82,19 @@ impl SecretRef {
|
||||
key: name.to_string(),
|
||||
name: name.to_string(),
|
||||
argv_placeholder: true,
|
||||
askpass: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Construct an askpass ref (v0.4) from a vault-internal name. The value
|
||||
/// is exposed to the child through an external helper script (read via
|
||||
/// `SSH_ASKPASS` etc.) — never placed in the child's argv or env.
|
||||
pub fn askpass(name: &str) -> Self {
|
||||
Self {
|
||||
key: name.to_string(),
|
||||
name: name.to_string(),
|
||||
argv_placeholder: false,
|
||||
askpass: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -107,6 +125,10 @@ pub struct ResolvedValue {
|
||||
/// the value is intended for argv substitution via `scrub_argv`, not
|
||||
/// for env injection via `build_envp_delta`.
|
||||
pub argv_placeholder: bool,
|
||||
/// Mirrors `SecretRef::askpass`. When `true`, the value is exposed to the
|
||||
/// child through an external helper script (set up by `run_exec`); it
|
||||
/// never enters the child's argv or env directly.
|
||||
pub askpass: bool,
|
||||
}
|
||||
|
||||
impl Clone for ResolvedValue {
|
||||
@@ -118,6 +140,7 @@ impl Clone for ResolvedValue {
|
||||
backend: self.backend.clone(),
|
||||
value: secrecy::SecretBox::new(Box::new(self.value.expose_secret().clone())),
|
||||
argv_placeholder: self.argv_placeholder,
|
||||
askpass: self.askpass,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -130,6 +153,7 @@ impl std::fmt::Debug for ResolvedValue {
|
||||
.field("backend", &self.backend)
|
||||
.field("value", &"<secret>")
|
||||
.field("argv_placeholder", &self.argv_placeholder)
|
||||
.field("askpass", &self.askpass)
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -204,6 +204,7 @@ pub async fn resolve_all(refs: &[SecretRef]) -> Result<Vec<ResolvedValue>> {
|
||||
backend: "local".into(),
|
||||
value: secret,
|
||||
argv_placeholder: r.argv_placeholder,
|
||||
askpass: r.askpass,
|
||||
});
|
||||
}
|
||||
// Vault drops at end of function — its key buffer is wiped via Drop.
|
||||
|
||||
+198
-2
@@ -197,7 +197,7 @@ fn run_masks_secret_in_child_stdout() {
|
||||
|
||||
#[test]
|
||||
fn run_masks_argv_placeholder_value() {
|
||||
// `xop://NAME` argv substitution puts the value into the child's argv;
|
||||
// `%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()
|
||||
@@ -214,13 +214,36 @@ fn run_masks_argv_placeholder_value() {
|
||||
.success();
|
||||
xop_bypass_auth()
|
||||
.env("XOP_VAULT_PASSWORD", "testpass")
|
||||
.args(["run", "--", "echo", "token=xop://PH"])
|
||||
.args(["run", "--", "echo", "token=%XOP_PH%"])
|
||||
.assert()
|
||||
.success()
|
||||
.stdout(predicate::str::contains("se****【xop禁止将密钥泄漏】"))
|
||||
.stdout(predicate::str::contains("secretvalue").not());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_rejects_v0_xop_key_placeholder_with_migration_message() {
|
||||
// v0.3 hard-cut: the v0.2 `xop://KEY` syntax is rejected with a clear
|
||||
// migration message in `expand_xop_placeholders` BEFORE the vault opens,
|
||||
// so this test doesn't even need a vault. We init one anyway for symmetry
|
||||
// with the run_masks_* tests (HOME is already set by make_vault).
|
||||
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(["run", "--", "echo", "token=xop://PH"])
|
||||
.assert()
|
||||
.failure()
|
||||
.code(64)
|
||||
.stderr(predicate::str::contains("xop://KEY 占位符在 v0.3 移除"))
|
||||
.stderr(predicate::str::contains("请改用 %XOP_KEY%"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keyring_enables_passphrase_free_unlock() {
|
||||
// Issue #3: after `xop init` writes the 0600 keyring, later ops unlock
|
||||
@@ -359,4 +382,177 @@ fn list_on_empty_vault() {
|
||||
.assert()
|
||||
.failure()
|
||||
.code(78); // vault not initialized
|
||||
}
|
||||
|
||||
// ─── v0.4 askpass tests ─────────────────────────────────────────────────────
|
||||
|
||||
// Init a vault with one secret. The returned TempDir MUST be bound (not
|
||||
// dropped) by the caller so the vault directory survives past init — see
|
||||
// `make_vault`'s pattern.
|
||||
fn init_vault_with_secret(name: &str, value: &str) -> tempfile::TempDir {
|
||||
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", "-f", name])
|
||||
.write_stdin(format!("{value}\n"))
|
||||
.assert()
|
||||
.success();
|
||||
home
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_askpass_sets_ssh_env_vars() {
|
||||
let _home = init_vault_with_secret("PH", "askpasstest");
|
||||
xop_bypass_auth()
|
||||
.env("XOP_VAULT_PASSWORD", "testpass")
|
||||
.args([
|
||||
"run",
|
||||
"--askpass=PH",
|
||||
"--",
|
||||
"sh", "-c",
|
||||
"echo SSH_ASKPASS=$SSH_ASKPASS; echo REQ=$SSH_ASKPASS_REQUIRE; \
|
||||
echo DISPLAY=$DISPLAY; echo DATA=$XOP_ASKPASS_DATA",
|
||||
])
|
||||
.assert()
|
||||
.success()
|
||||
// SSH_ASKPASS lands under std::env::temp_dir(): /tmp on Linux,
|
||||
// /var/folders/.../T (per-user, world-unreadable) on macOS via $TMPDIR.
|
||||
// Match the dynamic components rather than the full absolute prefix
|
||||
// (trailing slash conventions on std::env::temp_dir() differ by OS).
|
||||
.stdout(predicate::str::contains("SSH_ASKPASS="))
|
||||
.stdout(predicate::str::contains("/xop-askpass-"))
|
||||
.stdout(predicate::str::contains("/getpass.sh"))
|
||||
.stdout(predicate::str::contains("REQ=force"))
|
||||
.stdout(predicate::str::contains("DISPLAY=:0"))
|
||||
.stdout(predicate::str::contains("DATA="))
|
||||
.stdout(predicate::str::contains("/xop-askpass-"))
|
||||
.stdout(predicate::str::contains("/data"))
|
||||
.stdout(predicate::str::contains("askpasstest").not());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_askpass_script_outputs_value() {
|
||||
// The helper script at $SSH_ASKPASS should output the vault value when
|
||||
// invoked. To verify without triggering stdout-mask (which would redact
|
||||
// the value), we capture the script's stdout into a shell variable and
|
||||
// print only its length — the mask guard can't fire on a number.
|
||||
let _home = init_vault_with_secret("PH", "askpasstest"); // 11 chars
|
||||
xop_bypass_auth()
|
||||
.env("XOP_VAULT_PASSWORD", "testpass")
|
||||
.args([
|
||||
"run",
|
||||
"--askpass=PH",
|
||||
"--",
|
||||
"sh", "-c",
|
||||
"out=$($SSH_ASKPASS); echo ${#out}",
|
||||
])
|
||||
.assert()
|
||||
.success()
|
||||
.stdout(predicate::str::contains("11"))
|
||||
.stdout(predicate::str::contains("askpasstest").not());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_askpass_cleans_temp_dir_on_exit() {
|
||||
let _home = init_vault_with_secret("PH", "cleanupvalue");
|
||||
xop_bypass_auth()
|
||||
.env("XOP_VAULT_PASSWORD", "testpass")
|
||||
.args([
|
||||
"run",
|
||||
"--askpass=PH",
|
||||
"--",
|
||||
"sh", "-c", "true",
|
||||
])
|
||||
.assert()
|
||||
.success();
|
||||
// After xop run exits, /tmp/xop-askpass-* dirs created during the run
|
||||
// must be gone (Drop impl runs `srm -m` or fallback `rm -rf`).
|
||||
let remaining: Vec<_> = std::fs::read_dir(std::env::temp_dir())
|
||||
.unwrap()
|
||||
.filter_map(|e| e.ok())
|
||||
.filter(|e| {
|
||||
e.file_name().to_string_lossy().starts_with("xop-askpass-")
|
||||
})
|
||||
.collect();
|
||||
assert!(
|
||||
remaining.is_empty(),
|
||||
"askpass temp dir should be cleaned up after exit; found: {:?}",
|
||||
remaining.iter().map(|e| e.path()).collect::<Vec<_>>(),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_askpass_does_not_inject_value_as_env_var() {
|
||||
// --askpass=PH must NOT also set $PH in the child's env — the value is
|
||||
// reachable only via $SSH_ASKPASS. Verify by checking $PH is empty.
|
||||
let _home = init_vault_with_secret("PH", "secretvalue");
|
||||
xop_bypass_auth()
|
||||
.env("XOP_VAULT_PASSWORD", "testpass")
|
||||
.args([
|
||||
"run",
|
||||
"--askpass=PH",
|
||||
"--",
|
||||
"sh", "-c",
|
||||
"if [ -n \"$PH\" ]; then echo LEAK; else echo OK; fi",
|
||||
])
|
||||
.assert()
|
||||
.success()
|
||||
.stdout(predicate::str::contains("OK"))
|
||||
.stdout(predicate::str::contains("LEAK").not())
|
||||
.stdout(predicate::str::contains("secretvalue").not());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_askpass_unknown_key_fails() {
|
||||
let _home = init_vault_with_secret("PH", "x");
|
||||
xop_bypass_auth()
|
||||
.env("XOP_VAULT_PASSWORD", "testpass")
|
||||
.args([
|
||||
"run",
|
||||
"--askpass=MISSING",
|
||||
"--",
|
||||
"sh", "-c", "true",
|
||||
])
|
||||
.assert()
|
||||
.failure()
|
||||
.code(77) // KeyNotFound
|
||||
.stderr(predicate::str::contains("MISSING"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_askpass_combined_with_secret_env_injection() {
|
||||
// --askpass=SSH_PASS routes the password through SSH_ASKPASS; a separate
|
||||
// --secret DB_PASS=db_pass still goes via env injection. Verify both
|
||||
// paths work side by side.
|
||||
let _home = init_vault_with_secret("SSH_PASS", "s3cret");
|
||||
xop_bypass_auth()
|
||||
.env("XOP_VAULT_PASSWORD", "testpass")
|
||||
.args(["set", "-f", "DB_PASS"])
|
||||
.write_stdin("dbpass123\n")
|
||||
.assert()
|
||||
.success();
|
||||
xop_bypass_auth()
|
||||
.env("XOP_VAULT_PASSWORD", "testpass")
|
||||
.args([
|
||||
"run",
|
||||
"--askpass=SSH_PASS",
|
||||
"--secret", "DB_PASS=DB_PASS",
|
||||
"--",
|
||||
"sh", "-c",
|
||||
"echo DB=$DB_PASS; out=$($SSH_ASKPASS); echo AP_LEN=${#out}",
|
||||
])
|
||||
.assert()
|
||||
.success()
|
||||
// DB_PASS went via env injection → its value is in stdout, gets masked.
|
||||
.stdout(predicate::str::contains("db****【xop禁止将密钥泄漏】"))
|
||||
.stdout(predicate::str::contains("dbpass123").not())
|
||||
// SSH_PASS via askpass → only length printed.
|
||||
.stdout(predicate::str::contains("AP_LEN=6"))
|
||||
.stdout(predicate::str::contains("s3cret").not());
|
||||
}
|
||||
Reference in new issue
Block a user