Files
xop/tests/integration.rs
T
xop-botandClaude Code 7660b92d70 v0.5: 描述元数据 + list 免引号搜索 + 元数据操作免闸门
影响: key 多了人/AI 可读的用途说明(存加密 vault 内,不落明文文件);
`xop list` 的搜索不用再打引号; `xop list` / `xop desc` 只碰元数据、
永不吐 value,因此不再弹指纹、不再问口令 —— agent 跑 xop 不会被打断。
118 unit + 40 integration 全绿。

改动:
- 新增 `xop desc KEY [TEXT...]`: 描述存 vault 的 `__meta__` TOML 子表;
  文字用空格 join(不用引号), 真打进 vault 的一层引号会被剥掉;
  不写文字 = 清除描述(不用敲空引号 "")
- `xop list [TERM...]`: 搜索默认改成大小写不敏感的子串匹配, 命中 key 名
  或描述, 不用引号、不用通配符; 含 `*` `?` `[` 的词仍切 glob 语义
  (老写法 `xop list 'git_*'` 行为不变); 多词取并集
- 新增 `Vault::open_metadata` / `open_metadata_at`: 只开元数据路径,
  0600 keyring 静默解锁, 无 keyring 才回落手输 passphrase;
  `get`/`set`/`rm`/`run` 仍走 `Vault::open` 全套闸门
- 新增 `auth::Intent` + `auth::needs_gate(intent)`: 把"哪些操作要闸门"
  写成纯函数; `Vault::open` 与 `open_metadata` 共享 `decrypt_with` 核心
- 新增 `src/glob.rs`: 轻量匹配器, `*` 任意长 / `?` 单字符, 零新依赖;
  搜索用的 `has_meta` / `matches_ignore_case` / `contains_ignore_case` /
  `contains_glob_ignore_case`
- 新增 `src/datadir.rs`: 数据目录 `~/.xop/` → `~/.x/xop/`, 迁移是
  **复制不移动**(旧目录留作备份), 新 vault 已存在则跳过
- `keyring::load_at` / `save_at` 改 pub(路径显式化, 单测不碰全局 HOME)
- `audit.rs` 新增 `vault_desc(name)`: 只记 key 名, 描述文字不入日志(I2)
- 集成测试新增 pty 回归 `list_under_a_tty_never_prompts_for_biometrics`:
  `script -q /dev/null` 起真 pty + 30s 超时, 闸门若回来则失败而非挂死
- 版本 0.4.0 → 0.5.2; AGENTS.md / HANDOFF.md / docs/* 同步;
  examples 里 v0.5 搬家前的 `~/.xop/` 残留路径一并修正

设计: "搜索要打引号"的根因是 shell 通配符(`*` 在 zsh 下没匹配文件直接
`no matches found`), 不是 xop —— 所以正解不是"少打引号", 而是让日常
搜索根本不需要通配符: 默认子串匹配, `*`/`?`/`[` 只在用户显式写了时才
切回 glob。免闸门只给元数据操作: 闸门的意义是"释放真值前确认有人在场",
而 list/desc 永不吐 value; 值路径(get/set/rm/run)一行没动。

Co-Authored-By: Claude Code <[email protected]>
2026-10-22 17:03:12 +08:00

866 lines
28 KiB
Rust

//! 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 ~/.x/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 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
// 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
}
// ─── 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());
}
// ─── v0.5: descriptions + glob filtering ───────────────────────────────────
#[test]
fn desc_shows_up_in_list() {
// `xop desc KEY "文本"` attaches a description; `xop list` shows it next
// to the key name (and never the value).
let _home = init_vault_with_secret("git_local_user", "alice");
xop_bypass_auth()
.env("XOP_VAULT_PASSWORD", "testpass")
.args(["desc", "git_local_user", "GitLab 本地账号用户名"])
.assert()
.success()
.stdout(predicate::str::contains("git_local_user"));
xop_bypass_auth()
.env("XOP_VAULT_PASSWORD", "testpass")
.args(["list"])
.assert()
.success()
.stdout(predicate::str::contains("git_local_user"))
.stdout(predicate::str::contains("GitLab 本地账号用户名"))
// The value must never show up in the listing.
.stdout(predicate::str::contains("alice").not());
}
#[test]
fn list_filters_by_glob_pattern() {
let _home = init_vault_with_secret("git_local_user", "alice");
xop_bypass_auth()
.env("XOP_VAULT_PASSWORD", "testpass")
.args(["set", "-f", "llm_key"])
.write_stdin("sk-test\n")
.assert()
.success();
xop_bypass_auth()
.env("XOP_VAULT_PASSWORD", "testpass")
.args(["list", "git_*"])
.assert()
.success()
.stdout(predicate::str::contains("git_local_user"))
.stdout(predicate::str::contains("llm_key").not())
.stdout(predicate::str::contains("(1 of 2 total)"));
}
#[test]
fn list_pattern_matches_nothing() {
let _home = init_vault_with_secret("git_local_user", "alice");
xop_bypass_auth()
.env("XOP_VAULT_PASSWORD", "testpass")
.args(["list", "s19_*"])
.assert()
.success()
.stdout(predicate::str::contains("(no keys match)"))
.stdout(predicate::str::contains("git_local_user").not());
}
#[test]
fn list_search_needs_no_quotes_and_no_wildcard() {
let _home = init_vault_with_secret("git_local_user", "alice");
xop_bypass_auth()
.env("XOP_VAULT_PASSWORD", "testpass")
.args(["set", "-f", "llm_key"])
.write_stdin("sk-test\n")
.assert()
.success();
// A plain term is a substring match on the key name — no quoting, no `*`.
xop_bypass_auth()
.env("XOP_VAULT_PASSWORD", "testpass")
.args(["list", "git_local"])
.assert()
.success()
.stdout(predicate::str::contains("git_local_user"))
.stdout(predicate::str::contains("llm_key").not())
.stdout(predicate::str::contains("(1 of 2 total)"));
}
#[test]
fn list_search_is_case_insensitive() {
let _home = init_vault_with_secret("git_local_user", "alice");
xop_bypass_auth()
.env("XOP_VAULT_PASSWORD", "testpass")
.args(["list", "GIT_LOCAL"])
.assert()
.success()
.stdout(predicate::str::contains("git_local_user"));
}
#[test]
fn list_search_matches_a_description() {
let _home = init_vault_with_secret("git_local_user", "alice");
xop_bypass_auth()
.env("XOP_VAULT_PASSWORD", "testpass")
.args(["desc", "git_local_user", "GitLab 本地账号"])
.assert()
.success();
// The term hits the description, not the key name.
xop_bypass_auth()
.env("XOP_VAULT_PASSWORD", "testpass")
.args(["list", "GitLab"])
.assert()
.success()
.stdout(predicate::str::contains("git_local_user"))
.stdout(predicate::str::contains("(1 of 1 total)"));
}
#[test]
fn list_search_unions_several_terms() {
let _home = init_vault_with_secret("git_local_user", "alice");
xop_bypass_auth()
.env("XOP_VAULT_PASSWORD", "testpass")
.args(["set", "-f", "llm_key"])
.write_stdin("sk-test\n")
.assert()
.success();
xop_bypass_auth()
.env("XOP_VAULT_PASSWORD", "testpass")
.args(["list", "git_local", "llm"])
.assert()
.success()
.stdout(predicate::str::contains("git_local_user"))
.stdout(predicate::str::contains("llm_key"))
.stdout(predicate::str::contains("(2 of 2 total)"));
}
#[test]
fn list_names_only_omits_descriptions() {
let _home = init_vault_with_secret("git_local_user", "alice");
xop_bypass_auth()
.env("XOP_VAULT_PASSWORD", "testpass")
.args(["desc", "git_local_user", "某种用途"])
.assert()
.success();
xop_bypass_auth()
.env("XOP_VAULT_PASSWORD", "testpass")
.args(["list", "--names-only"])
.assert()
.success()
.stdout(predicate::str::contains("git_local_user"))
.stdout(predicate::str::contains("某种用途").not());
}
#[test]
fn desc_on_unknown_key_exits_77() {
let _home = init_vault_with_secret("PRESENT", "x");
xop_bypass_auth()
.env("XOP_VAULT_PASSWORD", "testpass")
.args(["desc", "MISSING", "说明"])
.assert()
.failure()
.code(77)
.stderr(predicate::str::contains("MISSING"));
}
#[test]
fn desc_with_empty_text_clears_the_description() {
let _home = init_vault_with_secret("K", "v");
xop_bypass_auth()
.env("XOP_VAULT_PASSWORD", "testpass")
.args(["desc", "K", "先写点什么"])
.assert()
.success();
xop_bypass_auth()
.env("XOP_VAULT_PASSWORD", "testpass")
.args(["desc", "K", ""])
.assert()
.success();
xop_bypass_auth()
.env("XOP_VAULT_PASSWORD", "testpass")
.args(["list"])
.assert()
.success()
.stdout(predicate::str::contains("K"))
.stdout(predicate::str::contains("先写点什么").not());
}
#[test]
fn desc_without_any_text_clears_the_description() {
// No empty quotes needed: omitting the text clears the description.
let _home = init_vault_with_secret("K", "v");
xop_bypass_auth()
.env("XOP_VAULT_PASSWORD", "testpass")
.args(["desc", "K", "先写点什么"])
.assert()
.success();
xop_bypass_auth()
.env("XOP_VAULT_PASSWORD", "testpass")
.args(["desc", "K"])
.assert()
.success()
.stdout(predicate::str::contains("description cleared"));
xop_bypass_auth()
.env("XOP_VAULT_PASSWORD", "testpass")
.args(["list"])
.assert()
.success()
.stdout(predicate::str::contains("先写点什么").not());
}
#[test]
fn desc_accepts_unquoted_multiple_words() {
// Typing quotes is a pain (input method, keyboard layout) — the words
// are joined with single spaces instead.
let _home = init_vault_with_secret("git_local_user", "alice");
xop_bypass_auth()
.env("XOP_VAULT_PASSWORD", "testpass")
.args(["desc", "git_local_user", "GitLab", "本地", "账号用户名"])
.assert()
.success();
xop_bypass_auth()
.env("XOP_VAULT_PASSWORD", "testpass")
.args(["list"])
.assert()
.success()
.stdout(predicate::str::contains("GitLab 本地 账号用户名"));
}
#[test]
fn desc_strips_quotes_the_user_typed_literally() {
// The shell usually eats the quotes, but pasted text or a script may keep
// them — strip one layer so the stored description is clean.
let _home = init_vault_with_secret("K", "v");
xop_bypass_auth()
.env("XOP_VAULT_PASSWORD", "testpass")
.args(["desc", "K", "\"带引号的说明\""])
.assert()
.success();
xop_bypass_auth()
.env("XOP_VAULT_PASSWORD", "testpass")
.args(["list"])
.assert()
.success()
.stdout(predicate::str::contains("带引号的说明"))
.stdout(predicate::str::contains("\"").not());
}
/// `xop list` must never interrupt an agent with a Touch ID popup or a
/// passphrase prompt — it only ever shows names and descriptions.
///
/// The test runs the binary under a real pty (`script -q /dev/null …`), so
/// `stdin.is_terminal()` is true inside xop. With the OS gate in that path a
/// biometric dialog would appear and the command would block; here it must
/// return immediately with the key names.
#[cfg(target_os = "macos")]
#[test]
fn list_under_a_tty_never_prompts_for_biometrics() {
let _home = init_vault_with_secret("git_local_user", "alice");
let bin = assert_cmd::cargo::cargo_bin("xop");
let home = std::env::var("HOME").unwrap();
let child = std::process::Command::new("script")
.args(["-q", "/dev/null", bin.to_str().unwrap(), "list"])
.env("HOME", home)
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.spawn()
.expect("spawn under pty");
// Bound the wait: if a biometric gate ever comes back, the child would
// block on the Touch ID dialog and this test would hang.
let (tx, rx) = std::sync::mpsc::channel();
std::thread::spawn(move || {
let out = child.wait_with_output().ok();
let _ = tx.send(out);
});
let output = rx
.recv_timeout(std::time::Duration::from_secs(30))
.expect("xop list must not block on a biometric prompt")
.expect("child output");
let stdout = String::from_utf8_lossy(&output.stdout).to_string();
assert!(output.status.success(), "xop list failed: {stdout}");
assert!(
stdout.contains("git_local_user"),
"expected the key name in the listing, got: {stdout}"
);
}
#[test]
fn rm_removes_the_description_too() {
let _home = init_vault_with_secret("K", "v");
xop_bypass_auth()
.env("XOP_VAULT_PASSWORD", "testpass")
.args(["desc", "K", "某种用途"])
.assert()
.success();
xop_bypass_auth()
.env("XOP_VAULT_PASSWORD", "testpass")
.args(["rm", "-f", "K"])
.assert()
.success();
xop_bypass_auth()
.env("XOP_VAULT_PASSWORD", "testpass")
.args(["list"])
.assert()
.success()
.stdout(predicate::str::contains("(no keys stored)"))
.stdout(predicate::str::contains("某种用途").not());
}
/// v0.5 moved the data dir from `~/.xop/` to `~/.x/xop/`. A vault left in
/// the old location must be picked up automatically (copied, not moved — the
/// legacy copy stays as the user's backup).
#[test]
fn legacy_vault_in_dot_xop_is_migrated_automatically() {
let home = init_vault_with_secret("LEGACY_KEY", "v");
// Pretend this vault was created by the pre-v0.5 layout.
let new_dir = home.path().join(".x").join("xop");
let legacy_dir = home.path().join(".xop");
std::fs::rename(&new_dir, &legacy_dir).unwrap();
xop_bypass_auth()
.env("XOP_VAULT_PASSWORD", "testpass")
.args(["list"])
.assert()
.success()
.stdout(predicate::str::contains("LEGACY_KEY"));
// The migration copied the vault into the new location...
assert!(new_dir.join("key.db").exists());
// ...and left the legacy copy alone.
assert!(legacy_dir.join("key.db").exists());
}