diff --git a/.agents/skills/agents-env/SKILL.md b/.agents/skills/agents-env/SKILL.md index 5a09d9a..52a16f2 100644 --- a/.agents/skills/agents-env/SKILL.md +++ b/.agents/skills/agents-env/SKILL.md @@ -2,13 +2,19 @@ name: agents-env description: >- Use and manage secrets/env vars through the `agents-env` CLI WITHOUT ever - putting the value into your own context. Use whenever you need to pass an API + putting the value into your own context. Use when you need to pass an API key, token, or secret to a command (curl, an SDK CLI, a test runner), build a project .env / .env.local from stored secrets, or find which env keys exist — without printing the value. Core verbs: run (inject into a child + mask its output + {{KEY}} argv substitution), copy (global store → local file, value never passes through you), get / ls (discovery; values hidden in agent - mode). The global master store is read-only for agents — never try to write it. + mode), and generate (append a new random global key without seeing its value). + Existing global credentials are never changed by agent commands. +metadata: + requires: + - tool: agents-env + check: agents-env --version + install: cargo install agents-env --- # agents-env @@ -32,7 +38,8 @@ agents-env config path Use the effective path from `config show`; respect existing settings and XDG resolution. A human can choose an existing store with `config set global_store` -or register new secrets through `edit`. Config changes are refused in agent +or register externally issued credentials through `edit`. Use `generate` for +new random keys owned by your own services. Config changes are refused in agent mode because redirecting the global store changes the write-protection boundary. Never remove agent markers to get around this check. Then use `agents-env doctor` to check setup and the harness deny rules. This works the same for Grok, @@ -118,6 +125,18 @@ agents-env copy GEMINI_API_KEY@personal --to .env.local agents-env set NEXT_PUBLIC_URL http://localhost:3000 --to .env.local # non-secret literals ``` +Create a random key for your own service without handling its value: +``` +agents-env generate SERVICE_API_KEY +agents-env run SERVICE_API_KEY -- my-service +``` + +Generation appends only to the configured global store. An existing name, +including case variants or tagged duplicates, is refused rather than replaced. +Malformed input is refused before saving; do not comment out old keys or repair +real credential files to force generation through. A busy store can be retried +after the other writer finishes. Generation cannot issue external provider keys. + ## Selectors and scope - `KEY@tag` picks one account when a key has several; the tag is the inline @@ -128,9 +147,10 @@ agents-env set NEXT_PUBLIC_URL http://localhost:3000 --to .env.local # non-sec ## Rules and limits -- **Never write the global store.** `set`/`copy` only write local `.env*` files - in the cwd; the global store is human-only (a human edits it with - `agents-env edit`). Don't fight the write guard — fix the actual target. +- **Only `generate` may append a new global key.** It never accepts or prints + a value and never changes an existing name. `set`/`copy` stay local-only; + humans use `edit` for existing or externally issued credentials. Do not + bypass the guards or read the store directly. - **Masking is defense in depth, not a sandbox.** It catches verbatim values, not re-encoded ones (base64, splitting). Reading `.env` files directly still exposes secrets — that is the harness deny-rule layer's job, not this tool's. diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index 90819cb..cf09eff 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -10,7 +10,7 @@ { "name": "agents-env", "source": "./", - "version": "0.2.0", + "version": "0.3.0", "description": "Skill that teaches an agent to use the agents-env CLI: inject secrets into commands without the value reaching the agent's context, copy global secrets into a project .env value-free, and discover keys without printing them.", "category": "security", "author": { diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json index 230e502..859f225 100644 --- a/.claude-plugin/plugin.json +++ b/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "agents-env", - "version": "0.2.0", + "version": "0.3.0", "description": "Env vars for AI agents: use secrets without ever seeing their values. Teaches the agent to inject API keys/tokens into commands (run + output masking + {{KEY}} substitution), copy secrets from a global store into a project .env without the value passing through context, and discover keys without printing them. Requires the `agents-env` CLI (cargo install agents-env).", "author": { "name": "Aiden Ahn", diff --git a/AGENTS.md b/AGENTS.md index 6de8df8..857204f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -27,11 +27,12 @@ This authorization covers the local CLI and its PR workflow. Registry publishing ## Architecture (one responsibility per module) -- `main.rs` — clap CLI + command handlers (`get`/`ls`/`run`/`set`/`copy`/`edit`/`doctor`/`config`), scope resolution, mask-set assembly. +- `main.rs` — clap CLI + command handlers (`get`/`ls`/`run`/`set`/`copy`/`generate`/`edit`/`doctor`/`config`), scope resolution, mask-set assembly. - `aimode.rs` — agent-mode detection from env markers (+ config `markers=`). - `config.rs` — typed settings loaded once per invocation, portable path resolution, guarded config edits. The global store resolves to an absolute path and is never per-command overridable. - `store.rs` — line-preserving `.env` parser, `KEY@tag` selector, round-trip editing. - `guard.rs` — write-side guards, backup, atomic write, git-ignore gate, secret heuristic. +- `generate.rs` — append-only global key generation, byte-preserving candidate validation, directory-relative transactions and the lock shared with human `edit` sessions. - `mask.rs` — child injection + leftmost-longest streaming output masking + `{{KEY}}` argv substitution. ## Security invariants — do not regress (each has a test) @@ -44,6 +45,8 @@ These are the product. A change that weakens one is a bug even if it compiles: 4. `set`/`copy` can only write bare `.env*` files in cwd; the global store is unreachable (no flag, path-separator/symlink/hardlink/samefile/cwd-in-store-dir-or-descendant all rejected). 5. Secret-bearing `copy` refuses git-tracked or non-gitignored targets (no override). 6. Writes back up to `.YYMMDD.bak` (first-of-day wins) then write atomically (`O_NOFOLLOW` temp + rename). +7. `generate` is the only agent-accessible global writer: OS-random new keys only, no caller value, replacement or tag option; ASCII case-insensitive existing names and malformed stores are refused before persistence. Existing bytes and parsed values/tags remain unchanged, and a generated key must be discoverable by the same parser/selector used by `get`/`run`. +8. Global generation and `edit` hold the same exclusive sidecar lock. Store, backup and staging protections fail closed; concurrent generation never loses an accepted key. Values never appear in generation output, including human mode. When adding a feature near these, add the adversarial test first. Known accepted limits are documented in README's threat model — don't "fix" them silently. diff --git a/Cargo.lock b/Cargo.lock index 6469f38..0fc1a6d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4,11 +4,12 @@ version = 4 [[package]] name = "agents-env" -version = "0.2.0" +version = "0.3.0" dependencies = [ "aho-corasick", "assert_cmd", "clap", + "getrandom", "libc", "predicates", "same-file", diff --git a/Cargo.toml b/Cargo.toml index 84198c4..1a799ac 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "agents-env" -version = "0.2.0" +version = "0.3.0" edition = "2024" rust-version = "1.88" description = "Env vars for AI agents — use secrets without ever seeing them" @@ -16,6 +16,7 @@ lto = true [dependencies] aho-corasick = "1.1.4" clap = { version = "4.6.1", features = ["derive"] } +getrandom = "0.4.2" libc = "0.2.186" same-file = "1.0.6" shlex = "1.3.0" diff --git a/README.en.md b/README.en.md index f60b9c6..1ce820e 100644 --- a/README.en.md +++ b/README.en.md @@ -27,7 +27,7 @@ There is no shortage of env and secret tools, but few keep the value out of the - **Output masking** — when an injected secret appears in the child's stdout/stderr, it is replaced with `[masked:KEY]` in real time. `doppler run` and `infisical run` inject but leave the output untouched. - **Value-free copy** — `copy` moves a secret from the global store into a local `.env` without the value passing through the agent's context. - **Agent-mode detection** — it auto-detects Grok, Codex, OpenCode, Claude Code, and AGY from runtime markers or parent CLI names; other assistants opt in with `AGENTS_ENV_AGENT_MODE=1` or `markers=`. -- **Asymmetric write guard** — the human-managed global master `.env` cannot be modified through this tool. +- **Asymmetric write guard** — existing global values remain human-managed. Agents may only append a new, internally generated random key with `generate`. ## How it works @@ -44,6 +44,7 @@ Masking only touches the output stream (child → caller); it never alters the i | `run -- ` | Inject into the child env, mask its output, substitute `{{KEY}}` in argv. `--all` injects the whole scope. | | `set --to ` | Write a non-secret value to a local file. Warns if it looks like a credential. | | `copy --to ` | Copy secrets from the global store into a local file; values are not printed. `--as NEWKEY` renames. | +| `generate ` | Add a new random key to the configured global store; refuse existing names and never print the value, even in human mode. | | `edit` | Open the global store in `$EDITOR`. Human only; refused in agent mode and on non-TTY. | | `doctor` | Check file permissions, gitignore coverage, stale backups, untagged duplicate keys, Claude Code deny rules. | | `config show` / `config path` | Show effective settings or the config path without reading secret values. | @@ -81,7 +82,8 @@ agents-env config reset editor ``` Changing settings does not create or move the secret store. Humans register -secrets with `agents-env edit`. Config writes preserve comments and other +externally issued credentials or change existing values with `agents-env edit`. +Use `generate` for new random keys owned by your own services. Config writes preserve comments and other settings, back up once per day, and use atomic 0600 writes. Unknown keys, duplicate settings, and read failures produce errors rather than silently falling back to defaults. Use `config reset global_store` instead of an empty @@ -109,6 +111,21 @@ agents-env -f .env.production get DATABASE agents-env copy NOTION_API_KEY@demodev --to .env.local ``` +## Generate without seeing the value + +```sh +agents-env generate SERVICE_API_KEY +agents-env run SERVICE_API_KEY -- my-service +``` + +`generate` encodes 32 OS-random bytes as 64 lowercase hexadecimal characters. It accepts only a key name, not a value, tag, overwrite or rotation option. `--local`/`--file` are refused: generation uses the same configured global path as `get`/`run`. It does not issue credentials for external providers. + +- Existing names are refused, including empty values, ASCII case variants and tagged duplicate accounts. No existing entry is replaced or commented out. +- Original bytes, comments, CRLF and order remain unchanged; only a separate entry is appended. A missing trailing newline is added as a separator. Before saving, the candidate is parsed again to verify unchanged existing values/tags and a unique, usable new key. +- Malformed lines, invalid UTF-8, NUL and any input whose meaning would change cause refusal before touching the store or backup. Errors name lines/reasons, never values. Comments are annotations and account selectors, not a duplicate-resolution mechanism. +- `generate` and `edit` share a stable exclusive lock. A busy store exits 2: retry after the other operation finishes. Retrying an existing name never rotates its key. +- Stores and backups use 0600, new parent directories use 0700. Links, special files and missing Git protection are refused; staging files must also be ignored. Generation backs up, publishes atomically and verifies the persisted key. + ## Write guard `set`/`copy` only write `.env*` files in the current directory. The global store is unreachable by construction. @@ -121,7 +138,7 @@ agents-env copy NOTION_API_KEY@demodev --to .env.local - Inside a git repo, a secret-bearing `copy` target must be both untracked and gitignored. Otherwise it is a hard error (no override; fix `.gitignore`). - Backups of existing targets must also be untracked and ignored for both `set` and `copy`. Use `.env*` rather than only `.env`; a Git verification failure refuses the copy. -Every write makes a `.YYMMDD.bak` backup first. From the second write of the day onward it keeps that day's first backup, since the state before the day's work is the recovery point. It then writes to an `O_NOFOLLOW` temp file and renames it into place. Backups also start with `.env`, so one `.env*` gitignore line covers them. +Every write makes a `.YYMMDD.bak` backup first. From the second write of the day onward it keeps that day's first backup, since the state before the day's work is the recovery point. It then writes to an `O_NOFOLLOW` temp file and renames it into place. Backups also start with `.env`, so one `.env*` gitignore line covers them. The exceptional global append through `generate` follows the narrower rules above. ## Limitations @@ -174,8 +191,8 @@ MY_AGENT_MODE=1 agents-env get TAVILY - **Detection is a signal, not a barrier.** Mode is decided from env markers and nearby parent CLI names, so an agent can reach human mode by hiding both. The intended threat is an honest agent that should not accidentally log a secret. Direct store access by a malicious agent is for the deny rules to stop, not this tool. - **`{{KEY}}` is visible to a same-user `ps`.** The value lands in the child's argv, where another process of the same user can read it. On a shared machine, use env injection instead of `{{KEY}}` for sensitive values. -- **Parent-directory-swap TOCTOU.** The guard canonicalizes cwd and uses `O_NOFOLLOW` on the temp file, but a same-user attacker who renames a parent directory mid-write could still redirect it. Closing this fully needs directory-fd (`openat`/`renameat`) writes, planned for a later version. It is unreachable without local same-user write access, and with that access the secrets are already exposed. -- **Line endings normalize to LF.** Round-trips preserve comments, order, and spacing, but a CRLF file is rewritten with LF and gains a trailing newline. +- **Concurrent editing boundary.** `generate` and `edit` share a lock. External editors do not follow it, so do not edit the store directly during generation. Generation uses directory-relative `openat`/`renameat` and rechecks changes before publishing, but is not a sandbox against malicious same-user mutation. Existing `set`/`copy` retain the parent-directory-swap race limit. +- **Line endings.** `generate` preserves existing bytes. Existing `set`/`copy` round-trips preserve comments, order and spacing, but rewrite CRLF as LF and add a trailing newline. ## Install diff --git a/README.md b/README.md index 712d411..cbbc94d 100644 --- a/README.md +++ b/README.md @@ -27,7 +27,7 @@ agents-env run TAVILY_API_KEY@work -- curl -H "Authorization: Bearer {{TAVILY_AP - **출력 마스킹**: 주입한 시크릿이 자식의 stdout/stderr에 나타나면 실시간으로 `[masked:KEY]`로 치환한다. `doppler run`·`infisical run`은 주입만 하고 출력은 막지 않는다. - **값 비경유 복사**: `copy`는 전역 store의 시크릿을 로컬 `.env`로 옮기되, 값이 에이전트 컨텍스트를 거치지 않는다. - **에이전트 모드 감지**: Grok, Codex, OpenCode, Claude Code, AGY는 런타임 마커나 부모 CLI 이름으로 자동 인식하고, 다른 어시스턴트는 `AGENTS_ENV_AGENT_MODE=1` 또는 `markers=`로 명시 opt-in한다. -- **비대칭 쓰기 가드**: 사람이 관리하는 전역 마스터 `.env`는 이 도구로 수정할 수 없다. +- **비대칭 쓰기 가드**: 기존 전역 키는 사람이 관리한다. 에이전트는 `generate`로 값이 노출되지 않는 새 무작위 키만 추가할 수 있다. ## 동작 방식 @@ -44,6 +44,7 @@ agents-env run TAVILY_API_KEY@work -- curl -H "Authorization: Bearer {{TAVILY_AP | `run -- ` | 자식 env에 주입, 출력 마스킹, argv의 `{{KEY}}` 치환. `--all`은 스코프 전체 주입. | | `set --to ` | 로컬 파일에 비밀이 아닌 값 기록. 크리덴셜 형태면 경고. | | `copy --to ` | 전역 store의 시크릿을 로컬 파일로 복사. 값은 출력하지 않음. `--as NEWKEY`로 키 이름 변경. | +| `generate ` | 설정된 전역 store에 새 무작위 키를 추가. 기존 이름은 거부하며, 값은 사람/에이전트 모두에게 출력하지 않음. | | `edit` | 전역 store를 `$EDITOR`로 연다. 사람 전용이며 에이전트 모드·비TTY에서는 거부. | | `doctor` | 파일 권한, gitignore 커버리지, 오래된 백업, 태그 없는 중복 키, Claude Code deny 규칙 점검. | | `config show` / `config path` | 시크릿 파일을 읽지 않고 유효 설정과 설정 파일 위치 조회. | @@ -79,8 +80,9 @@ agents-env config set markers 'MY_AGENT_MODE,MY_OTHER_AGENT' agents-env config reset editor ``` -설정 변경은 원래 `.env`를 이동하거나 생성하지 않는다. 새 시크릿은 사람이 -`agents-env edit`로 등록한다. `config set/reset`은 주석과 나머지 설정을 +설정 변경은 원래 `.env`를 이동하거나 생성하지 않는다. 외부 서비스에서 발급받은 +시크릿과 기존 키 수정은 사람이 `agents-env edit`로 처리한다. 자체 서비스용 새 +무작위 키는 `generate`로 만들 수 있다. `config set/reset`은 주석과 나머지 설정을 보존하며 변경 전 일별 백업과 0600 원자 쓰기를 사용한다. 알 수 없는 키, 중복 설정, 읽기 오류는 명시적으로 실패하며 조용히 기본값으로 대체하지 않는다. `global_store=`를 비우는 대신 `config reset global_store`로 복원할 수 있다. @@ -107,6 +109,21 @@ agents-env -f .env.production get DATABASE agents-env copy NOTION_API_KEY@demodev --to .env.local ``` +## 값을 보지 않고 새 키 생성 + +```sh +agents-env generate SERVICE_API_KEY +agents-env run SERVICE_API_KEY -- my-service +``` + +`generate`는 OS 난수 32바이트를 64자리 소문자 hex로 저장한다. 입력은 키 이름뿐이고 값, 태그, 덮어쓰기, 교체 옵션은 받지 않는다. `--local`/`--file`도 거부하며 `get`/`run`과 같은 설정된 전역 경로에만 쓴다. 외부 서비스의 API 키를 발급하는 기능은 아니다. + +- 기존 키가 있으면 빈 값, 대소문자만 다른 이름, 계정 태그가 있는 중복까지 모두 거부한다. 기존 키를 주석 처리하거나 갱신하지 않는다. +- 원본 바이트와 주석, CRLF, 줄 순서를 그대로 두고 마지막에 새 항목만 추가한다. 마지막 개행이 없으면 구분 개행을 추가한다. 완성된 내용을 다시 파싱해 기존 항목의 값과 태그가 같고 새 키가 유일하게 조회되는지 확인한 뒤 저장한다. +- 파싱할 수 없는 줄, 잘못된 UTF-8, NUL 또는 추가 후 의미가 바뀌는 원문이 있으면 파일과 백업을 건드리지 않고 실패한다. 오류에는 값 대신 줄 번호/원인만 표시한다. 주석은 설명과 기존 계정 선택용이지 중복 해결 수단이 아니다. +- 잠금은 동시에 실행한 `generate`와 `edit`를 직렬화한다. 사용 중이면 종료 코드 2로 거부하므로 완료 후 재시도한다. 같은 이름으로 재시도해도 이미 만든 키는 바뀌지 않는다. +- 파일과 백업은 0600, 새 상위 폴더는 0700으로 만들고, 링크/특수 파일과 Git 보호가 없는 대상은 거부한다. 임시 파일도 Git에서 제외되어야 한다. 저장 전 백업과 원자적 교체 후 재조회 검증을 거친다. + ## 쓰기 가드 `set`/`copy`는 현재 디렉토리의 `.env*` 파일만 쓴다. 전역 store는 구조적으로 도달할 수 없다. @@ -119,7 +136,7 @@ agents-env copy NOTION_API_KEY@demodev --to .env.local - git 레포 안에서는 시크릿을 쓰는 `copy` 타겟이 추적되지 않으면서 gitignore되어 있어야 한다. 아니면 하드 에러로 막는다(override 없음, `.gitignore` 수정 필요). - 기존 파일에 `set`/`copy`로 쓸 때는 백업도 Git에서 제외되어 있어야 한다. `.env` 한 줄만 제외하는 대신 `.env*`로 백업까지 보호한다. Git 검사 실패 시 복사하지 않는다. -쓰기 전에는 `.YYMMDD.bak` 백업을 만든다. 같은 날 두 번째 쓰기부터는 그날의 첫 백업을 유지한다(작업 시작 전 상태가 복구 지점이므로). 이후 `O_NOFOLLOW` 임시 파일에 쓰고 rename으로 교체한다. 백업도 `.env`로 시작하므로 `.env*` gitignore 한 줄로 함께 덮인다. +쓰기 전에는 `.YYMMDD.bak` 백업을 만든다. 같은 날 두 번째 쓰기부터는 그날의 첫 백업을 유지한다(작업 시작 전 상태가 복구 지점이므로). 이후 `O_NOFOLLOW` 임시 파일에 쓰고 rename으로 교체한다. 백업도 `.env`로 시작하므로 `.env*` gitignore 한 줄로 함께 덮인다. `generate`의 예외적인 전역 추가는 위 절의 더 좁은 규칙을 따른다. ## 한계 @@ -172,8 +189,8 @@ MY_AGENT_MODE=1 agents-env get TAVILY - **감지는 신호이지 차단막이 아니다.** 모드는 env 마커와 가까운 부모 CLI 이름으로 판단하므로, 에이전트가 마커를 제거하고 CLI 이름도 숨기면 사람 모드가 될 수 있다. 대상 위협은 실수로 시크릿을 로깅하면 안 되는 정직한 에이전트다. 악의적 에이전트가 store를 직접 읽는 것은 이 도구가 아니라 deny 규칙이 막을 영역이다. - **`{{KEY}}`는 같은 사용자의 `ps`에 노출된다.** 값이 자식 argv에 들어가 같은 사용자의 다른 프로세스가 읽을 수 있다. 공유 머신에서 민감한 값은 `{{KEY}}` 대신 env 주입을 사용한다. -- **부모 디렉토리 스왑 TOCTOU.** 가드가 cwd를 canonicalize하고 임시 파일에 `O_NOFOLLOW`를 쓰지만, 같은 사용자 권한의 공격자가 쓰기 도중 부모 디렉토리를 rename하면 우회할 수 있다. 완전한 차단은 디렉토리 fd(`openat`/`renameat`) 방식이 필요하며 다음 버전에서 다룬다. 로컬 동일 사용자 쓰기 권한 없이는 도달할 수 없고, 그 권한이 있다면 시크릿은 이미 노출된 상태다. -- **줄 끝은 LF로 정규화된다.** 라운드트립은 주석·순서·간격을 보존하지만 CRLF 파일은 LF로 다시 쓰이고 끝에 개행이 추가된다. +- **동시 편집의 경계.** `generate`와 `edit`는 같은 잠금을 사용한다. 도구 밖 편집기는 잠금을 따르지 않으므로 생성 중 직접 편집하지 않는다. 생성은 열린 디렉토리 fd(`openat`/`renameat`)를 사용하고 교체 전 파일 변경을 재확인하지만, 같은 사용자 권한의 악의적인 파일 교체까지 막는 샌드박스는 아니다. 기존 `set`/`copy`에는 부모 디렉토리 교체 경쟁의 한계가 있다. +- **줄 끝 보존.** `generate`는 기존 바이트를 정규화하지 않는다. 기존 `set`/`copy` 라운드트립은 주석·순서·간격을 보존하지만 CRLF를 LF로 쓰고 끝에 개행을 추가한다. ## 설치 diff --git a/src/config.rs b/src/config.rs index 6679bc5..19303a9 100644 --- a/src/config.rs +++ b/src/config.rs @@ -291,7 +291,7 @@ fn update_config(config: &Config, key: &str, value: Option<&str>) -> Result<(), .map_err(|e| format!("config write failed: {e}")) } -fn check_config_target(config: &Config) -> Result<(), String> { +pub(crate) fn check_config_target(config: &Config) -> Result<(), String> { use std::os::unix::fs::MetadataExt; // Config backups and staging files belong to the settings writer. A store // must never occupy one, including via a symlinked parent directory. diff --git a/src/generate.rs b/src/generate.rs new file mode 100644 index 0000000..079e06d --- /dev/null +++ b/src/generate.rs @@ -0,0 +1,418 @@ +//! The only agent-accessible global writer: add a new internally generated key. +//! Existing bytes are preserved, ambiguous/malformed input is refused, and all +//! file operations stay relative to an opened directory across atomic replacement. + +use crate::{config, guard, store}; +use std::ffi::{CString, OsStr}; +use std::fs::{self, File, Metadata}; +use std::io::{self, Read, Write}; +use std::os::fd::{AsRawFd, FromRawFd}; +use std::os::unix::fs::{DirBuilderExt, MetadataExt, OpenOptionsExt, PermissionsExt}; +use std::path::{Path, PathBuf}; + +type Failure = (i32, String); +type Result = std::result::Result; + +fn refused(message: impl Into) -> Failure { + (2, message.into()) +} + +fn io_error(operation: &str, error: io::Error) -> Failure { + (1, format!("{operation}: {error}")) +} + +fn regular_private_inode(metadata: &Metadata) -> Result<()> { + if !metadata.is_file() || metadata.nlink() != 1 || metadata.uid() != unsafe { libc::geteuid() } + { + return Err(refused( + "store, backup and lock must be owned regular files with one hard link", + )); + } + Ok(()) +} + +struct Directory { + file: File, + path: PathBuf, +} + +impl Directory { + fn open(path: &Path) -> Result { + let path = path + .canonicalize() + .map_err(|e| io_error("cannot resolve store directory", e))?; + let file = fs::OpenOptions::new() + .read(true) + .custom_flags(libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC) + .open(&path) + .map_err(|e| io_error("cannot open store directory", e))?; + Ok(Self { file, path }) + } + + fn open_file(&self, name: &str, flags: i32) -> io::Result { + let name = CString::new(name).map_err(|_| io::Error::other("invalid store file name"))?; + let fd = unsafe { + libc::openat( + self.file.as_raw_fd(), + name.as_ptr(), + flags | libc::O_NOFOLLOW | libc::O_CLOEXEC | libc::O_NONBLOCK, + 0o600, + ) + }; + if fd < 0 { + return Err(io::Error::last_os_error()); + } + let file = unsafe { File::from_raw_fd(fd) }; + if flags & libc::O_CREAT != 0 && flags & libc::O_EXCL != 0 { + // A restrictive caller umask must not publish an unreadable store. + file.set_permissions(fs::Permissions::from_mode(0o600))?; + } + Ok(file) + } + + fn remove_file(&self, name: &str) -> io::Result<()> { + let name = CString::new(name).map_err(|_| io::Error::other("invalid store file name"))?; + if unsafe { libc::unlinkat(self.file.as_raw_fd(), name.as_ptr(), 0) } < 0 { + return Err(io::Error::last_os_error()); + } + Ok(()) + } + + fn persist(&self, temporary: &str, name: &str, replace: bool) -> io::Result<()> { + let from = + CString::new(temporary).map_err(|_| io::Error::other("invalid temporary file name"))?; + let to = CString::new(name).map_err(|_| io::Error::other("invalid store file name"))?; + let fd = self.file.as_raw_fd(); + let result = if replace { + unsafe { libc::renameat(fd, from.as_ptr(), fd, to.as_ptr()) } + } else { + // Publishing a missing store must never overwrite one created in the meantime. + unsafe { libc::linkat(fd, from.as_ptr(), fd, to.as_ptr(), 0) } + }; + if result < 0 { + return Err(io::Error::last_os_error()); + } + if !replace { + self.remove_file(temporary)?; + } + self.file.sync_all() + } + + fn still_at(&self, parent: &Path) -> Result<()> { + let current = + fs::metadata(parent).map_err(|e| io_error("cannot recheck store directory", e))?; + let opened = self + .file + .metadata() + .map_err(|e| io_error("cannot inspect store directory", e))?; + if current.dev() != opened.dev() || current.ino() != opened.ino() { + return Err(refused("store directory changed; no key was added")); + } + Ok(()) + } +} + +struct Snapshot { + text: String, + metadata: Metadata, +} + +fn snapshot(directory: &Directory, name: &str) -> Result> { + let mut file = match directory.open_file(name, libc::O_RDONLY) { + Ok(file) => file, + Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(None), + Err(_) => { + return Err(refused( + "cannot safely open global store; check file type, links and permissions", + )); + } + }; + let metadata = file + .metadata() + .map_err(|e| io_error("cannot inspect global store", e))?; + regular_private_inode(&metadata)?; + let mut bytes = Vec::new(); + file.read_to_end(&mut bytes) + .map_err(|e| io_error("cannot read global store", e))?; + let text = String::from_utf8(bytes) + .map_err(|_| refused("global store is not valid UTF-8; no key was added"))?; + Ok(Some(Snapshot { text, metadata })) +} + +fn unchanged(directory: &Directory, name: &str, previous: Option<&Snapshot>) -> Result<()> { + let current = snapshot(directory, name)?; + let matches = match (previous, current.as_ref()) { + (None, None) => true, + (Some(old), Some(new)) => { + old.text == new.text + && old.metadata.dev() == new.metadata.dev() + && old.metadata.ino() == new.metadata.ino() + && old.metadata.mtime() == new.metadata.mtime() + && old.metadata.mtime_nsec() == new.metadata.mtime_nsec() + && old.metadata.ctime() == new.metadata.ctime() + && old.metadata.ctime_nsec() == new.metadata.ctime_nsec() + } + _ => false, + }; + if !matches { + return Err(refused( + "global store changed during generation; no key was added", + )); + } + Ok(()) +} + +/// Held across both generator transactions and human editor sessions. The stable +/// sidecar inode is never unlinked, so two waiters cannot lock different files. +pub(crate) struct StoreLock { + directory: Directory, + _file: File, + name: String, + parent: PathBuf, +} + +pub(crate) fn lock_store() -> Result { + config::check_config_target(config::current()).map_err(refused)?; + let target = config::global_store(); + let parent = target + .parent() + .ok_or_else(|| refused("global store must have a parent directory"))? + .to_path_buf(); + let name = target + .file_name() + .and_then(OsStr::to_str) + .ok_or_else(|| refused("global store must have a UTF-8 file name"))? + .to_string(); + if name.ends_with(".bak") || name.ends_with(".agents-env.lock") || name.ends_with(".tmp") { + return Err(refused( + "global store must not be a backup, lock or temporary file", + )); + } + fs::DirBuilder::new() + .recursive(true) + .mode(0o700) + .create(&parent) + .map_err(|e| io_error("cannot create store directory", e))?; + let directory = Directory::open(&parent)?; + let lock_name = format!("{name}.agents-env.lock"); + let file = match directory.open_file(&lock_name, libc::O_RDWR | libc::O_CREAT | libc::O_EXCL) { + Ok(file) => file, + Err(error) if error.kind() == io::ErrorKind::AlreadyExists => directory + .open_file(&lock_name, libc::O_RDWR) + .map_err(|_| refused("cannot safely open global store lock"))?, + Err(_) => return Err(refused("cannot safely create global store lock")), + }; + let metadata = file + .metadata() + .map_err(|e| io_error("cannot inspect global store lock", e))?; + regular_private_inode(&metadata)?; + if metadata.len() != 0 { + return Err(refused("global store lock must be an empty file")); + } + if metadata.mode() & 0o777 != 0o600 { + return Err(refused("global store lock must be private (0600)")); + } + if unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) } < 0 { + return Err(refused( + "global store is busy; retry after the other writer or editor finishes", + )); + } + directory.still_at(&parent)?; + Ok(StoreLock { + directory, + _file: file, + name, + parent, + }) +} + +fn candidate(text: &str, path: &Path, key: &str, value: &str) -> Result { + if text.contains('\0') { + return Err(refused( + "global store contains a NUL byte; no key was added", + )); + } + let original = store::EnvFile::parse(path, text); + if let Some(line) = original.unparseable_lines().first() { + return Err(refused(format!( + "global store line {} is not parseable; no key was added", + line + 1 + ))); + } + if original + .entries() + .any(|(_, entry)| entry.key.eq_ignore_ascii_case(key)) + { + return Err(refused(format!( + "{key} already exists (including tagged or case-variant entries); no key was added" + ))); + } + let newline = if text.contains("\r\n") { "\r\n" } else { "\n" }; + let mut output = text.to_string(); + if !output.is_empty() && !output.ends_with('\n') { + output.push_str(if output.ends_with('\r') { + "\n" + } else { + newline + }); + } + output.push_str(&format!( + "{key}=\"{value}\" # generated by agents-env{newline}" + )); + let parsed = store::EnvFile::parse(path, &output); + let old_count = original.entries().count(); + let preserved = original + .entries() + .zip(parsed.entries()) + .all(|((_, old), (_, new))| { + old.key == new.key && old.value == new.value && old.comment == new.comment + }); + if !parsed.unparseable_lines().is_empty() + || !preserved + || parsed.entries().count() != old_count + 1 + || !parsed + .select(key) + .is_ok_and(|(_, entry)| entry.key == key && entry.value == value) + { + return Err(refused( + "generated entry failed lookup verification; no key was added", + )); + } + Ok(output) +} + +fn backup(directory: &Directory, name: &str, previous: &Snapshot) -> Result<()> { + let name = format!("{name}.{}.bak", guard::yymmdd()); + match directory.open_file(&name, libc::O_RDONLY) { + Ok(file) => file, + Err(error) if error.kind() == io::ErrorKind::NotFound => { + return publish_backup(directory, &name, previous); + } + Err(_) => return Err(refused("existing backup is not safe")), + } + .metadata() + .map_err(|e| io_error("cannot inspect backup", e)) + .and_then(|metadata| { + regular_private_inode(&metadata)?; + if metadata.mode() & 0o777 != 0o600 { + return Err(refused("existing backup is not private; no key was added")); + } + Ok(()) + }) +} + +fn publish_backup(directory: &Directory, name: &str, previous: &Snapshot) -> Result<()> { + let temporary = format!("{name}.agents-env.{}.tmp", std::process::id()); + guard::git_secret_check(&directory.path, &temporary).map_err(refused)?; + let mut file = directory + .open_file(&temporary, libc::O_WRONLY | libc::O_CREAT | libc::O_EXCL) + .map_err(|_| refused("cannot safely create private backup staging file"))?; + let result = file + .write_all(previous.text.as_bytes()) + .and_then(|_| file.sync_all()) + .and_then(|_| directory.persist(&temporary, name, false)); + drop(file); + let _ = directory.remove_file(&temporary); + result.map_err(|e| io_error("cannot publish global store backup", e)) +} + +pub fn create(key: &str) -> Result<()> { + store::validate_key(key).map_err(|message| (3, message))?; + let locked = lock_store()?; + let directory = &locked.directory; + let path = directory.path.join(&locked.name); + guard::git_secret_check(&directory.path, &locked.name).map_err(refused)?; + let previous = snapshot(directory, &locked.name)?; + let text = previous + .as_ref() + .map_or("", |snapshot| snapshot.text.as_str()); + // Validate input and collisions before requesting randomness or creating a backup. + candidate(text, &path, key, "validation-only")?; + guard::git_backup_check(&path).map_err(refused)?; + let temporary = format!("{}.agents-env.{}.tmp", locked.name, std::process::id()); + guard::git_secret_check(&directory.path, &temporary).map_err(refused)?; + let mut bytes = [0u8; 32]; + getrandom::fill(&mut bytes).map_err(|_| { + ( + 1, + "operating system randomness failed; no key was added".to_string(), + ) + })?; + let mut value = String::with_capacity(64); + const HEX: &[u8] = b"0123456789abcdef"; + for byte in bytes { + value.push(HEX[(byte >> 4) as usize] as char); + value.push(HEX[(byte & 15) as usize] as char); + } + let output = candidate(text, &path, key, &value)?; + let mut file = directory + .open_file(&temporary, libc::O_WRONLY | libc::O_CREAT | libc::O_EXCL) + .map_err(|_| refused("cannot safely create private staging file"))?; + let transaction = (|| { + file.write_all(output.as_bytes()) + .and_then(|_| file.sync_all()) + .map_err(|e| io_error("cannot stage generated key", e))?; + directory.still_at(&locked.parent)?; + unchanged(directory, &locked.name, previous.as_ref())?; + if let Some(previous) = previous.as_ref() { + backup(directory, &locked.name, previous)?; + } + unchanged(directory, &locked.name, previous.as_ref())?; + directory + .persist(&temporary, &locked.name, previous.is_some()) + .map_err(|e| io_error("cannot publish generated key", e))?; + let saved = snapshot(directory, &locked.name)? + .ok_or_else(|| refused("cannot verify persisted generated key"))?; + if saved.text != output || saved.metadata.mode() & 0o777 != 0o600 { + return Err(refused( + "persisted key verification failed; inspect the store before retrying", + )); + } + Ok(()) + })(); + drop(file); + let _ = directory.remove_file(&temporary); + transaction +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn changed_or_replaced_store_is_detected_before_publishing() { + let root = tempfile::tempdir().unwrap(); + let path = root.path().join("global.env"); + fs::write(&path, "KEEP=fixture-original\n").unwrap(); + let directory = Directory::open(root.path()).unwrap(); + let before = snapshot(&directory, "global.env").unwrap().unwrap(); + fs::write(&path, "KEEP=fixture-edited\n").unwrap(); + assert_eq!( + unchanged(&directory, "global.env", Some(&before)) + .unwrap_err() + .0, + 2 + ); + let replacement = root.path().join("replacement"); + fs::write(&replacement, &before.text).unwrap(); + fs::rename(replacement, &path).unwrap(); + assert_eq!( + unchanged(&directory, "global.env", Some(&before)) + .unwrap_err() + .0, + 2 + ); + assert_eq!(fs::read_to_string(path).unwrap(), before.text); + } + + #[test] + fn replacing_parent_directory_is_detected() { + let root = tempfile::tempdir().unwrap(); + let parent = root.path().join("store"); + fs::create_dir(&parent).unwrap(); + let directory = Directory::open(&parent).unwrap(); + fs::rename(&parent, root.path().join("moved")).unwrap(); + fs::create_dir(&parent).unwrap(); + assert_eq!(directory.still_at(&parent).unwrap_err().0, 2); + } +} diff --git a/src/main.rs b/src/main.rs index fb7cf6e..2ab64b7 100644 --- a/src/main.rs +++ b/src/main.rs @@ -3,6 +3,7 @@ mod aimode; mod config; +mod generate; mod guard; mod mask; mod store; @@ -22,10 +23,13 @@ AGENT MODE (auto on Unix: Grok, Codex, OpenCode, Claude Code, AGY; opt-in: AGENT agents-env copy KEY@tag --to .env.local global store -> local file, value never passes through your context agents-env set PORT 3000 --to .env.local non-secret literals only + agents-env generate NEW_SERVICE_KEY create a new random global key; + never prints or replaces a value KEY@tag picks one of several accounts for the same key (tags come from the - inline '# comment' in the env file). The global store is read-only by - design: no flag of set/copy can reach it. Humans edit it with `agents-env edit`. + inline '# comment' in the env file). Only generate can add a new global key; + existing keys are never changed. set/copy remain local-only. Humans edit + existing or externally issued credentials with `agents-env edit`. Other assistants and renamed/deeply wrapped CLIs are supported by explicit opt-in: launch them with AGENTS_ENV_AGENT_MODE=1, or add a marker you set @@ -105,6 +109,8 @@ enum Cmd { #[arg(long = "as", value_name = "NEWKEY")] rename: Option, }, + /// Generate a new global key without seeing its value; never replace an existing key + Generate { key: String }, /// Open the global store in $EDITOR (humans only — refused in agent mode) Edit, /// Audit protection coverage: permissions, gitignore, backups, dup keys @@ -144,6 +150,22 @@ fn main() { to, rename, } => cmd_copy(selectors, to, rename.as_deref()), + Cmd::Generate { key } => { + if cli.local || cli.file.is_some() { + fail( + 3, + "generate only writes the configured global store; omit --local/--file", + ) + } else { + match generate::create(key) { + Ok(()) => { + println!("generated {key} [new global key; value hidden]"); + 0 + } + Err((code, message)) => fail(code, &message), + } + } + } Cmd::Edit => cmd_edit(), Cmd::Doctor => cmd_doctor(), }; @@ -567,13 +589,17 @@ fn cmd_edit() -> i32 { if aimode::agent_mode() { return fail( 2, - "edit is human-only. Agents: use `copy`/`set` on local files; the global store is read-only for you.", + "edit is human-only. Agents: use `generate` for a new random global key, or `copy`/`set` on local files; existing global values cannot be changed.", ); } let tty = unsafe { libc::isatty(0) == 1 && libc::isatty(1) == 1 }; if !tty { return fail(2, "edit requires an interactive terminal"); } + let _lock = match generate::lock_store() { + Ok(lock) => lock, + Err((code, message)) => return fail(code, &message), + }; let path = config::global_store(); if let Some(dir) = path.parent() && let Err(e) = std::fs::create_dir_all(dir) diff --git a/tests/generate.rs b/tests/generate.rs new file mode 100644 index 0000000..4a3fbf8 --- /dev/null +++ b/tests/generate.rs @@ -0,0 +1,541 @@ +//! Generation uses fake, isolated stores only; the user's real store is never read. +use assert_cmd::Command; +use std::fs; +use std::os::fd::AsRawFd; +use std::os::unix::fs::{MetadataExt, PermissionsExt}; +use std::path::{Path, PathBuf}; +use std::process::{Command as Process, Stdio}; +use std::time::Duration; +use tempfile::TempDir; + +struct Sandbox { + root: TempDir, + home: PathBuf, + cwd: PathBuf, + store: PathBuf, +} + +impl Sandbox { + fn new(contents: &[u8]) -> Self { + let root = TempDir::new().unwrap(); + let home = root.path().join("home"); + let cwd = root.path().join("project"); + let store = home.join(".config/agents-env/global.env"); + fs::create_dir_all(store.parent().unwrap()).unwrap(); + fs::create_dir_all(&cwd).unwrap(); + fs::write(&store, contents).unwrap(); + Self { + root, + home, + cwd, + store, + } + } + + fn cmd(&self) -> Command { + let mut command = Command::cargo_bin("agents-env").unwrap(); + command + .env_clear() + .env("PATH", std::env::var_os("PATH").unwrap()) + .env("HOME", &self.home) + .env("AGENTS_ENV_AGENT_MODE", "1") + .current_dir(&self.cwd) + .timeout(Duration::from_secs(15)); + command + } + + fn backup_files(&self) -> Vec { + fs::read_dir(self.store.parent().unwrap()) + .unwrap() + .map(|entry| entry.unwrap().path()) + .filter(|path| path.extension().is_some_and(|extension| extension == "bak")) + .collect() + } + + fn generate(&self, key: &str) -> String { + let result = self.cmd().args(["generate", key]).assert().success(); + let text = fs::read_to_string(&self.store).unwrap(); + let prefix = format!("{key}=\""); + let value = text + .lines() + .find_map(|line| line.strip_prefix(&prefix)) + .unwrap() + .split('"') + .next() + .unwrap() + .to_string(); + assert_eq!(value.len(), 64); + assert!( + value + .bytes() + .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte)) + ); + assert!(!String::from_utf8_lossy(&result.get_output().stdout).contains(&value)); + assert!(!String::from_utf8_lossy(&result.get_output().stderr).contains(&value)); + value + } +} + +fn git(cwd: &Path, arguments: &[&str]) { + assert!( + Process::new("git") + .args(arguments) + .current_dir(cwd) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .status() + .unwrap() + .success() + ); +} + +#[test] +fn generate_preserves_bytes_and_new_key_is_discoverable_and_masked() { + for original in [ + "# accounts\nOLD='fixture-old-value' # keep\n", + "# 마지막 주석 (개행 없음)", + "OLD=fixture-old-value", + "# header\r\nOLD=fixture-old-value\r\n", + "\n\nOLD=fixture-old-value # personal", + ] { + let sb = Sandbox::new(original.as_bytes()); + let value = sb.generate("NEW_KEY"); + assert!( + fs::read(&sb.store) + .unwrap() + .starts_with(original.as_bytes()) + ); + let found = sb.cmd().args(["get", "NEW_KEY"]).assert().success(); + let stdout = String::from_utf8_lossy(&found.get_output().stdout); + assert!(stdout.contains("NEW_KEY [set, 64 chars]")); + assert!(!stdout.contains(&value)); + let used = sb + .cmd() + .args([ + "run", + "NEW_KEY", + "--", + "sh", + "-c", + "printf '%s' \"$NEW_KEY\"; exit 17", + ]) + .assert() + .code(17); + assert_eq!(used.get_output().stdout, b"[masked:NEW_KEY]"); + assert!(!String::from_utf8_lossy(&used.get_output().stderr).contains(&value)); + assert_eq!(sb.backup_files().len(), 1); + assert_eq!( + fs::read(&sb.backup_files()[0]).unwrap(), + original.as_bytes() + ); + assert_eq!(fs::metadata(&sb.store).unwrap().mode() & 0o777, 0o600); + assert_eq!( + fs::metadata(&sb.backup_files()[0]).unwrap().mode() & 0o777, + 0o600 + ); + } +} + +#[test] +fn generate_rejects_existing_empty_tagged_and_case_variant_keys_without_changes() { + for original in [ + "KEY=fixture-original\n", + "KEY=\n", + "export KEY='fixture-original' # work\n", + "key=fixture-original\n", + "KEY=fixture-personal # personal\nKEY=fixture-work # work\n", + ] { + let sb = Sandbox::new(original.as_bytes()); + sb.cmd().args(["generate", "KEY"]).assert().code(2); + assert_eq!(fs::read(&sb.store).unwrap(), original.as_bytes()); + assert!(sb.backup_files().is_empty()); + } + let sb = Sandbox::new(b"KEEP=fixture-existing\n"); + sb.generate("NEW_KEY"); + let first = fs::read(&sb.store).unwrap(); + sb.cmd().args(["generate", "NEW_KEY"]).assert().code(2); + assert_eq!(fs::read(&sb.store).unwrap(), first); +} + +#[test] +fn unrelated_tagged_accounts_survive_and_select_as_before() { + let original = "API_KEY=fixture-personal # personal\nAPI_KEY=fixture-work # work\n"; + let sb = Sandbox::new(original.as_bytes()); + sb.generate("LOCAL_SERVICE_KEY"); + sb.cmd() + .args(["run", "API_KEY", "--", "true"]) + .assert() + .code(2); + let output = sb + .cmd() + .args([ + "run", + "API_KEY@work", + "--", + "sh", + "-c", + "test \"$API_KEY\" = fixture-work && printf '%s' \"$API_KEY\"", + ]) + .assert() + .success(); + assert_eq!(output.get_output().stdout, b"[masked:API_KEY]"); + assert!(fs::read_to_string(&sb.store).unwrap().starts_with(original)); +} + +#[test] +fn malformed_input_cannot_hide_a_key_or_leak_its_contents() { + for original in [ + b"KEY=fixture-old\nBAD=\"fixture-unclosed".as_slice(), + b"KEY =fixture-spaced\n", + b"export KEY =fixture-spaced\n", + b"KEY='fixture-value' trailing-secret\n", + b"\xef\xbb\xbfKEY=fixture-bom\n", + b"KEY=fixture\0value\n", + b"KEY=\xff\n", + b"KEY=fixture-original # trailing-comment\r", + ] { + let sb = Sandbox::new(original); + let output = sb.cmd().args(["generate", "NEW_KEY"]).assert().code(2); + let message = format!( + "{}{}", + String::from_utf8_lossy(&output.get_output().stdout), + String::from_utf8_lossy(&output.get_output().stderr) + ); + assert!(!message.contains("fixture")); + assert!(!message.contains("trailing-secret")); + assert_eq!(fs::read(&sb.store).unwrap(), original); + assert!(sb.backup_files().is_empty()); + } +} + +#[test] +fn generate_never_prints_value_in_human_mode_and_uses_no_caller_value() { + let sb = Sandbox::new(b""); + let output = sb + .cmd() + .env_remove("AGENTS_ENV_AGENT_MODE") + .args(["generate", "NEW_KEY"]) + .assert() + .success(); + let text = fs::read_to_string(&sb.store).unwrap(); + let value = text.split('"').nth(1).unwrap(); + assert!(!String::from_utf8_lossy(&output.get_output().stdout).contains(value)); + assert!(!String::from_utf8_lossy(&output.get_output().stderr).contains(value)); + for arguments in [ + vec!["generate", "KEY", "caller-secret"], + vec!["generate", "KEY@work"], + vec!["generate", "BAD=KEY"], + vec!["generate", "KEY", "--force"], + vec!["-l", "generate", "KEY"], + vec!["-f", ".env.local", "generate", "KEY"], + ] { + sb.cmd().args(arguments).assert().failure(); + assert_eq!(fs::read_to_string(&sb.store).unwrap(), text); + assert!(!sb.cwd.join(".env.local").exists()); + } +} + +#[test] +fn generate_honors_configured_store_and_creates_private_missing_store() { + let sb = Sandbox::new(b"DEFAULT=fixture-untouched\n"); + let destination = sb.root.path().join("new-private/store/custom.env"); + fs::write( + sb.home.join(".config/agents-env/config"), + format!("global_store={}\n", destination.display()), + ) + .unwrap(); + sb.cmd() + .args(["generate", "SERVICE_KEY"]) + .assert() + .success(); + assert_eq!( + fs::read_to_string(&sb.store).unwrap(), + "DEFAULT=fixture-untouched\n" + ); + assert_eq!(fs::metadata(&destination).unwrap().mode() & 0o777, 0o600); + assert_eq!( + fs::metadata(destination.parent().unwrap()).unwrap().mode() & 0o777, + 0o700 + ); + sb.cmd().args(["get", "SERVICE_KEY"]).assert().success(); + let empty = Sandbox::new(b""); + fs::remove_dir_all(&empty.home).unwrap(); + empty + .cmd() + .args(["generate", "FIRST_KEY"]) + .assert() + .success(); + assert_eq!(fs::metadata(&empty.store).unwrap().mode() & 0o777, 0o600); +} + +#[test] +fn generate_refuses_linked_or_nonregular_store_and_config_alias() { + for kind in ["symlink", "hardlink", "directory"] { + let sb = Sandbox::new(b"KEEP=fixture-original\n"); + let outside = sb.root.path().join("original"); + fs::rename(&sb.store, &outside).unwrap(); + match kind { + "symlink" => std::os::unix::fs::symlink(&outside, &sb.store).unwrap(), + "hardlink" => fs::hard_link(&outside, &sb.store).unwrap(), + _ => fs::create_dir(&sb.store).unwrap(), + } + sb.cmd().args(["generate", "NEW_KEY"]).assert().code(2); + assert_eq!(fs::read(&outside).unwrap(), b"KEEP=fixture-original\n"); + } + let sb = Sandbox::new(b"KEEP=fixture-original\n"); + let config = sb.home.join(".config/agents-env/config"); + fs::write(&config, "global_store=config\n").unwrap(); + sb.cmd().args(["generate", "NEW_KEY"]).assert().code(2); + assert_eq!( + fs::read_to_string(&config).unwrap(), + "global_store=config\n" + ); +} + +#[test] +fn lock_and_backup_symlinks_cannot_receive_existing_secrets() { + for suffix in ["agents-env.lock".to_string(), format!("{}.bak", date())] { + let sb = Sandbox::new(b"KEEP=fixture-original\n"); + let outside = sb.root.path().join("outside"); + let target = sb.store.with_file_name(format!("global.env.{suffix}")); + std::os::unix::fs::symlink(&outside, &target).unwrap(); + sb.cmd().args(["generate", "NEW_KEY"]).assert().code(2); + assert!(!outside.exists()); + assert_eq!(fs::read(&sb.store).unwrap(), b"KEEP=fixture-original\n"); + } +} + +fn date() -> String { + let output = Process::new("date").arg("+%y%m%d").output().unwrap(); + String::from_utf8(output.stdout).unwrap().trim().to_string() +} + +#[test] +fn git_protects_store_backup_and_private_staging_before_writing() { + for rule in ["", "global.env\n", "global.env\nglobal.env.*.bak\n"] { + let sb = Sandbox::new(b"KEEP=fixture-original\n"); + let directory = sb.store.parent().unwrap(); + git(directory, &["init", "-q"]); + fs::write(directory.join(".gitignore"), rule).unwrap(); + sb.cmd().args(["generate", "NEW_KEY"]).assert().code(2); + assert_eq!(fs::read(&sb.store).unwrap(), b"KEEP=fixture-original\n"); + assert!(sb.backup_files().is_empty()); + } + let sb = Sandbox::new(b"KEEP=fixture-original\n"); + let directory = sb.store.parent().unwrap(); + git(directory, &["init", "-q"]); + fs::write(directory.join(".gitignore"), "global.env*\n").unwrap(); + git(directory, &["add", "-f", "global.env"]); + sb.cmd().args(["generate", "NEW_KEY"]).assert().code(2); + assert_eq!(fs::read(&sb.store).unwrap(), b"KEEP=fixture-original\n"); + let good = Sandbox::new(b"KEEP=fixture-original\n"); + let directory = good.store.parent().unwrap(); + git(directory, &["init", "-q"]); + fs::write(directory.join(".gitignore"), "global.env*\n").unwrap(); + good.generate("NEW_KEY"); +} + +#[test] +fn concurrent_generators_preserve_every_successful_key_and_refuse_replacement() { + let sb = Sandbox::new(b"KEEP=fixture-original\n"); + let children: Vec<_> = (0..12) + .map(|number| { + let mut command = Process::new(env!("CARGO_BIN_EXE_agents-env")); + command + .env_clear() + .env("PATH", std::env::var_os("PATH").unwrap()) + .env("HOME", &sb.home) + .env("AGENTS_ENV_AGENT_MODE", "1") + .current_dir(&sb.cwd) + .args(["generate", &format!("KEY_{number}")]) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .unwrap() + }) + .collect(); + let results: Vec<_> = children + .into_iter() + .map(|child| child.wait_with_output().unwrap()) + .collect(); + for (number, output) in results.into_iter().enumerate() { + if !output.status.success() { + assert_eq!(output.status.code(), Some(2)); + sb.generate(&format!("KEY_{number}")); + } + } + let original = fs::read_to_string(&sb.store).unwrap(); + assert!(original.starts_with("KEEP=fixture-original\n")); + for number in 0..12 { + let key = format!("KEY_{number}"); + assert_eq!( + original + .lines() + .filter(|line| line.starts_with(&format!("{key}="))) + .count(), + 1 + ); + sb.cmd().args(["get", &key]).assert().success(); + sb.cmd().args(["generate", &key]).assert().code(2); + } + assert_eq!(fs::read_to_string(&sb.store).unwrap(), original); + assert_eq!( + fs::read(&sb.backup_files()[0]).unwrap(), + b"KEEP=fixture-original\n" + ); +} + +#[test] +fn locked_store_is_refused_without_writing_and_can_retry_after_unlock() { + let sb = Sandbox::new(b"KEEP=fixture-original\n"); + let path = sb.store.with_file_name("global.env.agents-env.lock"); + let lock = fs::File::create(&path).unwrap(); + fs::set_permissions(&path, fs::Permissions::from_mode(0o600)).unwrap(); + assert_eq!( + unsafe { libc::flock(lock.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) }, + 0 + ); + sb.cmd().args(["generate", "NEW_KEY"]).assert().code(2); + assert_eq!(fs::read(&sb.store).unwrap(), b"KEEP=fixture-original\n"); + assert!(sb.backup_files().is_empty()); + drop(lock); + sb.generate("NEW_KEY"); +} + +#[test] +fn concurrent_same_key_has_at_most_one_success_and_never_rotates() { + let sb = Sandbox::new(b"KEEP=fixture-original\n"); + let children: Vec<_> = (0..8) + .map(|_| { + Process::new(env!("CARGO_BIN_EXE_agents-env")) + .env_clear() + .env("PATH", std::env::var_os("PATH").unwrap()) + .env("HOME", &sb.home) + .env("AGENTS_ENV_AGENT_MODE", "1") + .current_dir(&sb.cwd) + .args(["generate", "ONE_KEY"]) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .unwrap() + }) + .collect(); + let results: Vec<_> = children + .into_iter() + .map(|child| child.wait_with_output().unwrap()) + .collect(); + assert_eq!( + results + .iter() + .filter(|output| output.status.success()) + .count(), + 1 + ); + assert!( + results + .iter() + .all(|output| output.status.success() || output.status.code() == Some(2)) + ); + let saved = fs::read_to_string(&sb.store).unwrap(); + assert_eq!( + saved + .lines() + .filter(|line| line.starts_with("ONE_KEY=")) + .count(), + 1 + ); + sb.cmd().args(["generate", "ONE_KEY"]).assert().code(2); + assert_eq!(fs::read_to_string(&sb.store).unwrap(), saved); +} + +#[test] +fn unsafe_fifo_lock_and_backup_are_refused_without_hanging_or_changing_keys() { + for kind in [ + "store-fifo", + "lock-fifo", + "backup-fifo", + "lock-hardlink", + "backup-hardlink", + "backup-public", + ] { + let sb = Sandbox::new(b"KEEP=fixture-original\n"); + let outside = sb.root.path().join("outside"); + let target = if kind.starts_with("lock") { + sb.store.with_file_name("global.env.agents-env.lock") + } else if kind.starts_with("backup") { + sb.store + .with_file_name(format!("global.env.{}.bak", date())) + } else { + fs::rename(&sb.store, &outside).unwrap(); + sb.store.clone() + }; + if kind.ends_with("fifo") { + use std::os::unix::ffi::OsStrExt; + let name = std::ffi::CString::new(target.as_os_str().as_bytes()).unwrap(); + assert_eq!(unsafe { libc::mkfifo(name.as_ptr(), 0o600) }, 0); + } else if kind.ends_with("hardlink") { + fs::write(&outside, b"fixture-outside\n").unwrap(); + fs::hard_link(&outside, &target).unwrap(); + } else { + fs::write(&target, b"fixture-public-backup\n").unwrap(); + fs::set_permissions(&target, fs::Permissions::from_mode(0o644)).unwrap(); + } + sb.cmd().args(["generate", "NEW_KEY"]).assert().code(2); + if kind == "store-fifo" { + assert_eq!(fs::read(&outside).unwrap(), b"KEEP=fixture-original\n"); + } else { + assert_eq!(fs::read(&sb.store).unwrap(), b"KEEP=fixture-original\n"); + } + } +} + +#[test] +fn commented_examples_do_not_become_active_duplicates() { + let original = "# NEW_KEY=example-not-an-active-secret\nKEEP=fixture-old\n"; + let sb = Sandbox::new(original.as_bytes()); + sb.generate("NEW_KEY"); + assert!(fs::read_to_string(&sb.store).unwrap().starts_with(original)); + sb.cmd().args(["get", "NEW_KEY"]).assert().success(); +} + +#[test] +fn restrictive_umask_does_not_publish_unreadable_keys() { + let sb = Sandbox::new(b"KEEP=fixture-original\n"); + let output = Process::new("sh") + .env_clear() + .env("PATH", std::env::var_os("PATH").unwrap()) + .env("HOME", &sb.home) + .env("AGENTS_ENV_AGENT_MODE", "1") + .current_dir(&sb.cwd) + .args([ + "-c", + "umask 0777; exec \"$1\" generate NEW_KEY", + "sh", + env!("CARGO_BIN_EXE_agents-env"), + ]) + .output() + .unwrap(); + assert!( + output.status.success(), + "{}", + String::from_utf8_lossy(&output.stderr) + ); + assert_eq!(fs::metadata(&sb.store).unwrap().mode() & 0o777, 0o600); + assert_eq!( + fs::metadata(&sb.backup_files()[0]).unwrap().mode() & 0o777, + 0o600 + ); + sb.cmd().args(["get", "NEW_KEY"]).assert().success(); +} + +#[test] +fn missing_git_cannot_bypass_global_write_protection() { + let sb = Sandbox::new(b"KEEP=fixture-original\n"); + sb.cmd() + .env("PATH", sb.root.path().join("no-tools")) + .args(["generate", "NEW_KEY"]) + .assert() + .code(2); + assert_eq!(fs::read(&sb.store).unwrap(), b"KEEP=fixture-original\n"); + assert!(sb.backup_files().is_empty()); +}