diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index cf09eff..b06bb6b 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -10,7 +10,7 @@ { "name": "agents-env", "source": "./", - "version": "0.3.0", + "version": "0.3.1", "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 859f225..6312ee8 100644 --- a/.claude-plugin/plugin.json +++ b/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "agents-env", - "version": "0.3.0", + "version": "0.3.1", "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/Cargo.lock b/Cargo.lock index 0fc1a6d..e1cfdfa 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4,7 +4,7 @@ version = 4 [[package]] name = "agents-env" -version = "0.3.0" +version = "0.3.1" dependencies = [ "aho-corasick", "assert_cmd", diff --git a/Cargo.toml b/Cargo.toml index 1a799ac..9fd2496 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "agents-env" -version = "0.3.0" +version = "0.3.1" edition = "2024" rust-version = "1.88" description = "Env vars for AI agents — use secrets without ever seeing them" diff --git a/README.en.md b/README.en.md index 1ce820e..2d39063 100644 --- a/README.en.md +++ b/README.en.md @@ -46,7 +46,7 @@ Masking only touches the output stream (child → caller); it never alters the i | `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. | +| `doctor` | Check global-store syntax/read errors, permissions, gitignore, stale backups, untagged duplicates and Claude Code deny rules. Never prints values or malformed source lines. | | `config show` / `config path` | Show effective settings or the config path without reading secret values. | | `config set ` / `config reset ` | Change one setting or restore its default; refused in agent mode. | @@ -101,6 +101,8 @@ from writes. Prefer the default location or a dedicated `~/secrets/` directory. **Scope and files.** The default scope is the global store. `-l`/`--local` reads `./.env`; `-f ` reads `./`, which handles `.env.local`, `.env.production`, and the like. +The reader recognizes existing digit-prefixed names without renaming or rewriting them. New names supplied to `set`, `generate` and `copy --as` still require portable `[A-Za-z_][A-Za-z0-9_]*` identifiers. Use a program's environment API rather than `$NAME` shell syntax for digit-prefixed names. + ``` agents-env -f .env.production get DATABASE ``` @@ -123,6 +125,7 @@ agents-env run SERVICE_API_KEY -- my-service - 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. +- When syntax blocks generation, use `agents-env doctor` for value-free reasons from the same parser. Do not print or ignore the malformed source line. - `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. diff --git a/README.md b/README.md index cbbc94d..c427d76 100644 --- a/README.md +++ b/README.md @@ -46,7 +46,7 @@ agents-env run TAVILY_API_KEY@work -- curl -H "Authorization: Bearer {{TAVILY_AP | `copy --to ` | 전역 store의 시크릿을 로컬 파일로 복사. 값은 출력하지 않음. `--as NEWKEY`로 키 이름 변경. | | `generate ` | 설정된 전역 store에 새 무작위 키를 추가. 기존 이름은 거부하며, 값은 사람/에이전트 모두에게 출력하지 않음. | | `edit` | 전역 store를 `$EDITOR`로 연다. 사람 전용이며 에이전트 모드·비TTY에서는 거부. | -| `doctor` | 파일 권한, gitignore 커버리지, 오래된 백업, 태그 없는 중복 키, Claude Code deny 규칙 점검. | +| `doctor` | 전역 저장소 문법/읽기 오류, 파일 권한, gitignore, 오래된 백업, 태그 없는 중복 키, Claude Code deny 규칙 점검. 값이나 문제 행 원문은 출력하지 않음. | | `config show` / `config path` | 시크릿 파일을 읽지 않고 유효 설정과 설정 파일 위치 조회. | | `config set ` / `config reset ` | 설정 한 항목을 변경하거나 기본값으로 복원. 에이전트 모드에서는 변경 거부. | @@ -99,6 +99,8 @@ agents-env config reset editor **스코프와 파일.** 기본 스코프는 전역 store다. `-l`/`--local`은 `./.env`를, `-f `은 `./`을 읽어 `.env.local`, `.env.production` 등 여러 파일을 다룬다. +읽기 파서는 기존 파일의 숫자로 시작하는 이름도 인식하며 이름이나 값을 바꾸지 않는다. 새 이름을 받는 `set`, `generate`, `copy --as`는 이식 가능한 `[A-Za-z_][A-Za-z0-9_]*` 형식을 계속 요구한다. 숫자로 시작하는 환경변수는 `$NAME` 셸 문법으로 접근하지 말고 프로그램의 환경변수 API로 사용한다. + ``` agents-env -f .env.production get DATABASE ``` @@ -121,6 +123,7 @@ agents-env run SERVICE_API_KEY -- my-service - 기존 키가 있으면 빈 값, 대소문자만 다른 이름, 계정 태그가 있는 중복까지 모두 거부한다. 기존 키를 주석 처리하거나 갱신하지 않는다. - 원본 바이트와 주석, CRLF, 줄 순서를 그대로 두고 마지막에 새 항목만 추가한다. 마지막 개행이 없으면 구분 개행을 추가한다. 완성된 내용을 다시 파싱해 기존 항목의 값과 태그가 같고 새 키가 유일하게 조회되는지 확인한 뒤 저장한다. - 파싱할 수 없는 줄, 잘못된 UTF-8, NUL 또는 추가 후 의미가 바뀌는 원문이 있으면 파일과 백업을 건드리지 않고 실패한다. 오류에는 값 대신 줄 번호/원인만 표시한다. 주석은 설명과 기존 계정 선택용이지 중복 해결 수단이 아니다. +- 문법 오류로 중단되면 `agents-env doctor`로 같은 파서의 값 없는 진단을 확인한다. 문제가 있는 행의 원문을 출력하거나 무시하지 않는다. - 잠금은 동시에 실행한 `generate`와 `edit`를 직렬화한다. 사용 중이면 종료 코드 2로 거부하므로 완료 후 재시도한다. 같은 이름으로 재시도해도 이미 만든 키는 바뀌지 않는다. - 파일과 백업은 0600, 새 상위 폴더는 0700으로 만들고, 링크/특수 파일과 Git 보호가 없는 대상은 거부한다. 임시 파일도 Git에서 제외되어야 한다. 저장 전 백업과 원자적 교체 후 재조회 검증을 거친다. diff --git a/src/generate.rs b/src/generate.rs index 079e06d..83c39d3 100644 --- a/src/generate.rs +++ b/src/generate.rs @@ -233,9 +233,9 @@ fn candidate(text: &str, path: &Path, key: &str, value: &str) -> Result )); } let original = store::EnvFile::parse(path, text); - if let Some(line) = original.unparseable_lines().first() { + if let Some((line, reason)) = original.syntax_issues().next() { return Err(refused(format!( - "global store line {} is not parseable; no key was added", + "global store line {} is not parseable: {reason}; no key was added", line + 1 ))); } diff --git a/src/main.rs b/src/main.rs index 2ab64b7..63fd375 100644 --- a/src/main.rs +++ b/src/main.rs @@ -113,7 +113,7 @@ enum Cmd { Generate { key: String }, /// Open the global store in $EDITOR (humans only — refused in agent mode) Edit, - /// Audit protection coverage: permissions, gitignore, backups, dup keys + /// Audit syntax, permissions, gitignore, backups and duplicate keys without printing values Doctor, } @@ -653,8 +653,11 @@ fn cmd_edit() -> i32 { // Post-edit lint: keep the KEY@tag selector scheme intact. Names and line // numbers only — never values. if let Ok(f) = EnvFile::load(&path) { - for idx in f.unparseable_lines() { - println!("{YELLOW}lint:{RESET} line {} is not parseable", idx + 1); + for (index, reason) in f.syntax_issues() { + println!( + "{YELLOW}lint:{RESET} line {} is not parseable: {reason}", + index + 1 + ); } let mut seen: Vec = Vec::new(); for (i, e) in f.entries() { @@ -694,21 +697,31 @@ fn cmd_doctor() -> i32 { warnings += 1; println!(" warn: permissions {mode:o} — consider chmod 600"); } - if let Ok(f) = EnvFile::load(&gpath) { - let mut seen: Vec = Vec::new(); - for (_, e) in f.entries() { - if f.occurrences(&e.key).len() > 1 - && e.comment.is_none() - && !seen.contains(&e.key) - { - seen.push(e.key.clone()); + match EnvFile::load(&gpath) { + Ok(f) => { + for (index, reason) in f.syntax_issues() { warnings += 1; - println!( - " warn: duplicate key {} has untagged entries (KEY@tag selection)", - e.key - ); + println!(" warn: line {} is not parseable: {reason}", index + 1); + } + let mut seen: Vec = Vec::new(); + for (_, e) in f.entries() { + if f.occurrences(&e.key).len() > 1 + && e.comment.is_none() + && !seen.contains(&e.key) + { + seen.push(e.key.clone()); + warnings += 1; + println!( + " warn: duplicate key {} has untagged entries (KEY@tag selection)", + e.key + ); + } } } + Err(_) => { + warnings += 1; + println!(" warn: cannot read global store as UTF-8; no contents were printed"); + } } } Err(_) => { diff --git a/src/store.rs b/src/store.rs index 164ec03..bfc33a9 100644 --- a/src/store.rs +++ b/src/store.rs @@ -24,6 +24,21 @@ pub struct Entry { pub struct Line { pub raw: String, pub entry: Option, + error: Option<&'static str>, +} + +impl Line { + fn parse(raw: &str) -> Self { + let (entry, error) = match parse_entry(raw) { + Ok(entry) => (entry, None), + Err(error) => (None, Some(error)), + }; + Self { + raw: raw.to_string(), + entry, + error, + } + } } #[derive(Debug)] @@ -40,9 +55,9 @@ pub enum SelectError { /// Validate a key before inserting it into an env file. /// -/// The parser accepts exactly this shell-style identifier grammar. Keeping the -/// write-side check in the same module prevents a user-supplied key from -/// injecting a newline, another assignment, or other raw file structure. +/// New writes use portable shell-style identifiers. Reading also accepts +/// digit-prefixed existing dotenv names without renaming them. This write-side +/// check prevents inserting a newline, assignment or other raw file structure. pub fn validate_key(key: &str) -> Result<(), String> { let mut chars = key.chars(); let Some(first) = chars.next() else { @@ -74,13 +89,7 @@ impl EnvFile { } pub fn parse(path: &Path, text: &str) -> EnvFile { - let lines = text - .lines() - .map(|l| Line { - raw: l.to_string(), - entry: parse_entry(l), - }) - .collect(); + let lines = text.lines().map(Line::parse).collect(); EnvFile { path: path.to_path_buf(), lines, @@ -156,8 +165,7 @@ impl EnvFile { .clone(); let mut raw = line.raw.clone(); raw.replace_range(span, new_value_raw); - line.entry = parse_entry(&raw); - line.raw = raw; + *line = Line::parse(&raw); } pub fn append(&mut self, key: &str, value_raw: &str, comment: Option<&str>) { @@ -165,10 +173,7 @@ impl EnvFile { Some(c) => format!("{key}={value_raw} {c}"), None => format!("{key}={value_raw}"), }; - self.lines.push(Line { - entry: parse_entry(&raw), - raw, - }); + self.lines.push(Line::parse(&raw)); } /// Line indices where `key` appears (exact, case-sensitive — write side). @@ -181,16 +186,15 @@ impl EnvFile { /// Lines that are neither blank, full-line comments, nor parseable entries. pub fn unparseable_lines(&self) -> Vec { + self.syntax_issues().map(|(index, _)| index).collect() + } + + /// Static reasons and line numbers only; no source text, keys or values. + pub fn syntax_issues(&self) -> impl Iterator + '_ { self.lines .iter() .enumerate() - .filter(|(_, l)| { - l.entry.is_none() - && !l.raw.trim().is_empty() - && !l.raw.trim_start().starts_with('#') - }) - .map(|(i, _)| i) - .collect() + .filter_map(|(index, line)| line.error.map(|error| (index, error))) } pub fn serialize(&self) -> String { @@ -216,14 +220,23 @@ pub fn quote_value(v: &str) -> String { format!("\"{escaped}\"") } -fn parse_entry(raw: &str) -> Option { +fn parse_entry(raw: &str) -> Result, &'static str> { + if raw.contains('\0') { + return Err("NUL bytes are not supported"); + } + if raw.starts_with('\u{feff}') { + return Err("a UTF-8 byte order mark is not supported"); + } + if raw.trim().is_empty() || raw.trim_start().starts_with('#') { + return Ok(None); + } let bytes = raw.as_bytes(); let mut i = 0; while i < bytes.len() && (bytes[i] == b' ' || bytes[i] == b'\t') { i += 1; } if i >= bytes.len() || bytes[i] == b'#' { - return None; + return Ok(None); } if raw[i..].starts_with("export ") || raw[i..].starts_with("export\t") { i += 7; @@ -232,15 +245,35 @@ fn parse_entry(raw: &str) -> Option { } } let key_start = i; - if i >= bytes.len() || !(bytes[i].is_ascii_alphabetic() || bytes[i] == b'_') { - return None; + if i >= bytes.len() || !(bytes[i].is_ascii_alphanumeric() || bytes[i] == b'_') { + return Err(if raw[i..].starts_with("//") || raw[i..].starts_with(';') { + "only '#' starts a dotenv comment; other comment markers are not supported" + } else if raw[i..].starts_with('[') { + "section headers are not supported in dotenv files" + } else if raw[i..].starts_with(['\'', '"']) { + "a quoted line without a variable name is not an assignment; multiline values are not supported" + } else if raw[i..].starts_with('`') { + "backtick or Markdown syntax is not supported in dotenv files" + } else if raw[i..].starts_with(char::is_whitespace) { + "only ASCII spaces and tabs may precede a variable name" + } else if !raw[i..].is_ascii() { + "a variable name must use ASCII letters, digits or underscores" + } else { + "expected an environment variable name followed by '='" + }); } while i < bytes.len() && (bytes[i].is_ascii_alphanumeric() || bytes[i] == b'_') { i += 1; } let key = raw[key_start..i].to_string(); if i >= bytes.len() || bytes[i] != b'=' { - return None; + return Err( + if i < bytes.len() && (bytes[i] == b' ' || bytes[i] == b'\t') { + "whitespace between a variable name and '=' is not supported" + } else { + "expected '=' immediately after the variable name" + }, + ); } i += 1; let vstart = i; @@ -299,12 +332,14 @@ fn parse_entry(raw: &str) -> Option { } } if !closed { - return None; + return Err("unterminated double-quoted value; multiline values are not supported"); } (val, j) } else if i < bytes.len() && bytes[i] == b'\'' { let rest = &raw[i + 1..]; - let p = rest.find('\'')?; + let p = rest + .find('\'') + .ok_or("unterminated single-quoted value; multiline values are not supported")?; (rest[..p].to_string(), i + 1 + p + 1) } else { // Bare value: runs until a `#` preceded by whitespace, or end of line. @@ -329,15 +364,15 @@ fn parse_entry(raw: &str) -> Option { None } else { // Trailing garbage after a quoted value — not a well-formed entry. - return None; + return Err("unexpected characters after a quoted value"); }; - Some(Entry { + Ok(Some(Entry { key, value, value_span: vstart..vend, comment, - }) + })) } #[cfg(test)] @@ -364,6 +399,21 @@ mod tests { assert_eq!(entries[1].1.value, "plain"); } + #[test] + fn reads_existing_numeric_names_without_relaxing_write_validation() { + let source = "1SERVICE_KEY=\"fixture-existing\" # work\n123='fixture-number'\n"; + let file = EnvFile::parse(Path::new("fixture"), source); + assert!(file.unparseable_lines().is_empty()); + assert_eq!( + file.select("1service_key@work").unwrap().1.value, + "fixture-existing" + ); + assert_eq!(file.select("123").unwrap().1.value, "fixture-number"); + assert_eq!(file.serialize(), source); + assert!(validate_key("1SERVICE_KEY").is_err()); + assert!(validate_key("123").is_err()); + } + #[test] fn replace_value_preserves_everything_else() { let src = "# header\n\nA=\"old\" # tag-a\nB=keep\n"; @@ -404,6 +454,25 @@ mod tests { assert_eq!(f.unparseable_lines(), vec![0]); } + #[test] + fn syntax_diagnostics_never_echo_source_or_values() { + let file = EnvFile::parse( + Path::new("fixture"), + "# comment\nKEY =fixture-secret\nBAD=\"fixture-secret\nOTHER='fixture-secret\n", + ); + let issues: Vec<_> = file.syntax_issues().collect(); + assert_eq!(issues.len(), 3); + assert_eq!(issues[0].0, 1); + assert!(issues[0].1.contains("whitespace")); + assert!(issues[1].1.contains("double-quoted")); + assert!(issues[2].1.contains("single-quoted")); + assert!( + issues + .iter() + .all(|(_, reason)| !reason.contains("fixture-secret")) + ); + } + #[test] fn backslash_before_multibyte_does_not_panic() { // Unknown escape `\é`: the lead byte of é must not be treated as one diff --git a/tests/cli.rs b/tests/cli.rs index 253e194..d3d27b9 100644 --- a/tests/cli.rs +++ b/tests/cli.rs @@ -917,6 +917,56 @@ fn edit_refused_in_agent_mode_and_non_tty() { assert_eq!(fs::read_to_string(sb.global_path()).unwrap(), GLOBAL); } +#[test] +fn doctor_reports_parse_failures_without_printing_source() { + let sb = Sandbox::new(); + for (source, reason) in [ + ( + "PRIVATE_KEY =fixture-sensitive-value\n", + "whitespace between a variable name and '='", + ), + ( + "PRIVATE_KEY=\"fixture-sensitive-value\n", + "unterminated double-quoted value", + ), + ( + "PRIVATE_KEY='fixture-sensitive-value\n", + "unterminated single-quoted value", + ), + ( + "PRIVATE_KEY=\"fixture-sensitive-value\" trailing\n", + "unexpected characters after a quoted value", + ), + ("PRIVATE_KEY=fixture-sensitive-value\0\n", "NUL bytes"), + ] { + fs::write(sb.global_path(), format!("# header\n{source}")).unwrap(); + let result = sb.cmd(true).arg("doctor").assert().code(1); + let text = String::from_utf8_lossy(&result.get_output().stdout); + assert!(text.contains("line 2 is not parseable")); + assert!(text.contains(reason)); + assert!(!text.contains("PRIVATE_KEY")); + assert!(!text.contains("fixture-sensitive-value")); + assert!(!text.contains("ok: no warnings")); + assert_eq!( + fs::read_to_string(sb.global_path()).unwrap(), + format!("# header\n{source}") + ); + } +} + +#[test] +fn doctor_reports_invalid_utf8_without_printing_bytes() { + let sb = Sandbox::new(); + let original = b"PRIVATE_KEY=fixture-sensitive-value\xff\n"; + fs::write(sb.global_path(), original).unwrap(); + let result = sb.cmd(true).arg("doctor").assert().code(1); + let text = String::from_utf8_lossy(&result.get_output().stdout); + assert!(text.contains("cannot read global store as UTF-8")); + assert!(!text.contains("PRIVATE_KEY")); + assert!(!text.contains("fixture-sensitive-value")); + assert_eq!(fs::read(sb.global_path()).unwrap(), original); +} + // ---------------------------------------------------------------- local scope #[test] diff --git a/tests/generate.rs b/tests/generate.rs index 4a3fbf8..9838cf2 100644 --- a/tests/generate.rs +++ b/tests/generate.rs @@ -182,6 +182,41 @@ fn unrelated_tagged_accounts_survive_and_select_as_before() { assert!(fs::read_to_string(&sb.store).unwrap().starts_with(original)); } +#[test] +fn numeric_existing_keys_are_preserved_discoverable_and_masked() { + let original = "# fixture accounts\r\n1SERVICE_KEY='fixture-numeric-value' # old\r\n"; + let sb = Sandbox::new(original.as_bytes()); + sb.generate("NEW_KEY"); + assert!( + fs::read(&sb.store) + .unwrap() + .starts_with(original.as_bytes()) + ); + let found = sb.cmd().args(["get", "1SERVICE_KEY"]).assert().success(); + let stdout = String::from_utf8_lossy(&found.get_output().stdout); + assert!(stdout.contains("1SERVICE_KEY")); + assert!(!stdout.contains("fixture-numeric-value")); + let result = sb + .cmd() + .args(["run", "1SERVICE_KEY@old", "--", "env"]) + .assert() + .success(); + assert!( + String::from_utf8_lossy(&result.get_output().stdout) + .contains("1SERVICE_KEY=[masked:1SERVICE_KEY]") + ); + assert!( + !String::from_utf8_lossy(&result.get_output().stdout).contains("fixture-numeric-value") + ); + let before = fs::read(&sb.store).unwrap(); + sb.cmd().args(["generate", "1SERVICE_KEY"]).assert().code(3); + assert_eq!(fs::read(&sb.store).unwrap(), before); + assert_eq!( + fs::read(&sb.backup_files()[0]).unwrap(), + original.as_bytes() + ); +} + #[test] fn malformed_input_cannot_hide_a_key_or_leak_its_contents() { for original in [ @@ -398,6 +433,9 @@ fn locked_store_is_refused_without_writing_and_can_retry_after_unlock() { 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()); + // Explicitly release the lock before retrying. A concurrent test can be + // between fork and exec and briefly retain a duplicate of this descriptor. + assert_eq!(unsafe { libc::flock(lock.as_raw_fd(), libc::LOCK_UN) }, 0); drop(lock); sb.generate("NEW_KEY"); }