Repository navigation
Description
Problem Statement
OpenCodeReview currently documents and examples LLM credentials primarily through configuration files and environment variables such as OCR_LLM_AUTH_TOKEN. This works well in CI, but it is not ideal for local CLI usage on developer machines.
Environment variables can leak through shell history, child process inheritance, process inspection, crash logs, and CI logs. Plain config files are also risky unless users manage permissions carefully.
Proposed Solution
Add first-class OS keyring support for local credentials.
The CLI could provide commands such as:
ocr auth key save <name> <token>
ocr auth key save <name> --stdin
ocr auth key save <name> --prompt
ocr auth key list
ocr auth key delete <name>
The direct form includes the token value; the stdin/prompt forms are safer because they avoid shell history and process-list exposure. Configuration could reference a named credential instead of storing the secret value. At runtime, auth resolution could use this precedence:
- Explicit CLI option.
- Named keyring credential.
- Existing config value.
- Environment variable fallback.
Suggested design
- Use a cross-platform keyring library where possible.
- Support macOS Keychain, Windows Credential Manager, and Linux Secret Service.
- Detect unavailable, denied, or locked keyrings with actionable messages.
- Keep environment variables supported for CI.
- Consider an encrypted file fallback for headless Linux if implemented carefully with restrictive permissions and clear warnings.
Reference implementation
LLxprt Code has a similar multi-platform design using @napi-rs/keyring with an encrypted fallback. It stores only a key name in profiles and resolves the secret at runtime.
Useful references at commit a50837636f124130cf2d6973d0641e2f4eae02c2:
SecureStoreadapter/options: https://github.com/vybestack/llxprt-code/blob/a50837636f124130cf2d6973d0641e2f4eae02c2/packages/core/src/storage/secure-store.ts#L56-L75- Dynamic
@napi-rs/keyringloader: https://github.com/vybestack/llxprt-code/blob/a50837636f124130cf2d6973d0641e2f4eae02c2/packages/core/src/storage/secure-store.ts#L156-L218 - Keyring availability probe: https://github.com/vybestack/llxprt-code/blob/a50837636f124130cf2d6973d0641e2f4eae02c2/packages/core/src/storage/secure-store.ts#L347-L399
- Keyring-first get/set with encrypted fallback: https://github.com/vybestack/llxprt-code/blob/a50837636f124130cf2d6973d0641e2f4eae02c2/packages/core/src/storage/secure-store.ts#L404-L500
/key savecommand: https://github.com/vybestack/llxprt-code/blob/a50837636f124130cf2d6973d0641e2f4eae02c2/packages/cli/src/ui/commands/keyCommand.ts#L66-L145/key loadcommand: https://github.com/vybestack/llxprt-code/blob/a50837636f124130cf2d6973d0641e2f4eae02c2/packages/cli/src/ui/commands/keyCommand.ts#L155-L217auth-key-nameresolution before environment variables: https://github.com/vybestack/llxprt-code/blob/a50837636f124130cf2d6973d0641e2f4eae02c2/packages/core/src/auth/precedence.ts#L645-L650- Documentation explaining why keyring is preferred over environment variables: https://github.com/vybestack/llxprt-code/blob/a50837636f124130cf2d6973d0641e2f4eae02c2/docs/cli/authentication.md#L62-L134
Acceptance criteria
- Users can save and reference an LLM auth token by name without putting the raw token in config, shell history, or environment variables.
- Existing environment variable workflows continue to work.
- Missing, denied, or locked keyring errors are clear and actionable.
- Documentation explains local keyring usage and CI secret usage separately.
中文说明
问题陈述
OpenCodeReview 目前主要通过配置文件和环境变量(例如 OCR_LLM_AUTH_TOKEN)来记录和演示 LLM 凭据。这种方式在 CI 环境中很好用,但在开发者本地 CLI 场景中并不理想。
环境变量可能通过 shell 历史记录、子进程继承、进程检查、崩溃日志以及 CI 日志等途径泄露。如果用户没有仔细管理文件权限,明文配置文件同样存在风险。
建议方案
为本地凭据提供一等公民的操作系统 keyring 支持。
CLI 可以提供类似下面的命令:
ocr auth key save <name> <token>
ocr auth key save <name> --stdin
ocr auth key save <name> --prompt
ocr auth key list
ocr auth key delete <name>
直接形式包含 token 值;stdin/prompt 形式更安全,因为可以避免写入 shell 历史记录或暴露在进程列表中。配置中可以引用一个命名凭据,而不是直接保存密钥明文。运行时的认证解析可以采用以下优先级:
- 显式 CLI 参数。
- 命名的 keyring 凭据。
- 现有配置值。
- 环境变量回退。
设计建议
- 尽量使用跨平台 keyring 库。
- 支持 macOS Keychain、Windows Credential Manager 和 Linux Secret Service。
- 当 keyring 不可用、被拒绝访问或处于锁定状态时,给出可操作的错误提示。
- 继续保留环境变量支持,以适配 CI 场景。
- 对于无桌面环境的 headless Linux,可以考虑加密文件回退,但需要严格的文件权限和清晰的安全提示。
参考实现
LLxprt Code 已经有类似的多平台设计:使用 @napi-rs/keyring,并提供加密文件回退。它在 profile 中只保存密钥名称,在运行时解析实际密钥。
上面的英文部分列出了具体代码和文档链接。
验收标准
- 用户可以按名称保存和引用 LLM auth token,不需要把原始 token 放进配置文件、shell 历史记录或环境变量。
- 现有环境变量工作流继续可用。
- 当 keyring 缺失、拒绝访问或被锁定时,错误信息清晰且可操作。
- 文档分别说明本地 keyring 使用方式和 CI secret 使用方式。
Activity
lizhengfeng101 commentedon Jun 29, 2026
Hi @acoliver, thank you for taking the time to write such a thorough and well-researched proposal! The security concerns you raised about environment variable leakage are absolutely valid, and we appreciate you thinking about how to make credential management safer for local usage.
After some consideration, our current inclination is to keep the CLI surface area lean and avoid introducing a built-in keyring subsystem. Our main concerns are:
Added complexity for users — A new
ocr auth keysubcommand family, a 4-level auth precedence chain, and cross-platform keyring edge cases (locked keyrings, missing Secret Service on headless Linux, encrypted file fallbacks) would add significant cognitive overhead for what is primarily a code review tool.Maintenance burden — Supporting macOS Keychain, Windows Credential Manager, and Linux Secret Service (plus fallbacks) across platforms is a non-trivial ongoing commitment for a relatively niche use case.
Existing ecosystem solutions — Most developers already have access to excellent secret management tools that integrate seamlessly with environment variables:
These approaches give users the same security benefits (no plaintext in config/history) with zero changes to OCR itself, and they work with any CLI tool — not just ours.
We think the best path forward is to document these patterns in our authentication guide so users are aware of secure alternatives, rather than building a parallel keyring system into the CLI.
That said, we're open to hearing more thoughts! If there's a use case where the external-tool approach falls short, we'd love to understand it better.
Thanks again for the thoughtful issue! 🙏
acoliver commentedon Jun 29, 2026
@lizhengfeng101 — agreed, let's drop the keyring subsystem. Cross-platform keyring brings real failure-mode surface (locked keychains in CI, no Secret Service on headless Linux), and that's not worth it for a CLI. Withdrawn.
But the specific fix is worth a closer look.
export OCR_LLM_AUTH_TOKEN=$(…)moves the token out of the config file and into the process environment, which is a widely-documented weaker surface for secrets:envcommand or inspecting the/proc/self/environfile," and "Any subprocess... will automatically inherit all of the parent's environment variables."For ocr specifically, it shells out to
git(and could spawn more), so every child inherits the token.A ~20-line change keeps the spirit of your recommendation, with no env leak and no keyring dependency — the same credential-command pattern git (
credential.helper), Docker, and AWS (credential_process) already use. One field:{ "providers": { "anthropic": { "api_key_cmd": "op read \"op://vault/ocr/token\"" } } }ocr execs the command, captures stdout, and holds the token in process memory only — never exported, never inherited by children. Your own examples become non-leaky versions of themselves:
api_key_cmd(memory-only)export OCR_LLM_AUTH_TOKEN=$(op read …)api_key_cmd: op read "op://vault/ocr/token"export …=$(security find-generic-password …)api_key_cmd: security find-generic-password -s ocr-token -wexport …=$(pass show ocr/token)api_key_cmd: pass show ocr/tokenexport …=$(bw get password ocr-token)api_key_cmd: bw get password ocr-tokenOne caveat (the thing to get right): the command must retrieve the secret from a vault, not embed it — otherwise it leaks via the process argument list (
ps//proc/<pid>/cmdline, readable by any user). The patterns above all retrieve, so they're safe.Same UX and tools you're already recommending, zero keyring maintenance — just no token in the environment. Happy to PR this if you're open to it.
lizhengfeng101 commentedon Jun 30, 2026
@acoliver — Great follow-up. We agree that
api_key_cmdis a much better scoping than the original keyring proposal. The credential-command pattern is well-established (gitcredential.helper, AWScredential_process), and it neatly avoids both plaintext-in-config and token-in-environment without adding any platform-specific dependencies on our side.Before we move forward, it would be helpful to see a more concrete proposal that covers the full picture — specifically:
1. System behavior change (before vs. after)
Today, OCR resolves a token from static sources only: config file fields (
api_key/auth_token) and environment variables. How exactly would the resolution change? For example, where doesapi_key_cmdsit in the precedence chain relative toapi_keyand the env-var fallback? What happens when the command fails (non-zero exit, empty stdout, timeout)?2. User behavior change (before vs. after)
A concrete walkthrough would be great — what does a user do today vs. what would they do with
api_key_cmd? For instance:ocr config setapi_keytoapi_key_cmdocr providerinteractive TUI — does it need changes, or is CLI-only sufficient for the first iteration?3. Backward compatibility
We want to make sure existing users are completely unaffected. Could you spell out the guarantees? e.g.:
api_keyin config continues to work as-isANTHROPIC_API_KEY,OCR_LLM_TOKEN, etc.) are unchangedapi_keyandapi_key_cmdare present — which wins, or is that an error?llm.auth_tokenfield — does it also get a correspondingauth_token_cmd?4. Config examples
A before/after
config.jsonshowing preset providers, custom providers, and the legacyllmsection would make the scope very clear.We are leaning toward accepting this — just want to make sure we have a shared understanding of the full scope before a PR lands. Thanks again for pushing on this!
chethanuk commentedon Jul 17, 2026
Picking up @lizhengfeng101's four questions with a concrete design for
api_key_cmd/auth_token_cmd. I'd like to implement this and want sign-off on the shape before any PR.1. System behavior change (before vs. after)
Resolution precedence, per provider entry (single change site in
tryProviderConfig, so preset providers andcustom_providersbehave identically):api_keyin configapi_keyandapi_key_cmdare set, the static key is used and one warning is printed to stderr (not an error — a hard error would break configs that set the command as a fallback)api_key_cmd(new)ANTHROPIC_API_KEY,DASHSCOPE_API_KEY, …)api_key_cmdCommand execution:
sh -c "<cmd>"on Unix,cmd /C "<cmd>"on Windows, selected via build-tag file pairs (keycmd_unix.go/keycmd_windows.go, mirroring the existingcmd/opencodereview/shell_unix.go/shell_windows.goconvention).exec.CommandContextwith a 60-second timeout (same default as AWS SDKcredential_process). The child's stderr passes through to OCR's stderr, so pinentry/1Password/opprompts stay visible. Stdout isTrimSpaced and used in memory only — never written to config or logs.Failure handling — always a hard error, never a silent fallback (a misconfigured credential command falling back to an env var would be a security surprise):
api_key_cmd for provider "x" failed: exit status 3api_key_cmd for provider "x" produced empty outputNo caching, by design: endpoint resolution runs once per process invocation, so the command (and any pinentry prompt) fires at most once per
ocrrun. There is nothing to cache and no daemon state.2. User behavior change (before vs. after)
Today (plaintext key in config):
ocr config set providers.anthropic.api_key sk-ant-...After — first-time setup with a secret manager:
Migration from an existing
api_key:ocr config setprints the command unmasked — deliberately: the value is a command line, not a secret (the existing masking correctly keys offapi_key/auth_tokensuffixes and won't matchapi_key_cmd).TUI (
ocr provider): no UI changes in v1 — CLI-only is sufficient for the first iteration. However, the TUI's internal clone/re-create paths must preserve the new field so that opening the TUI and re-saving a provider doesn't silently drop a configuredapi_key_cmd:cloneProviderEntryand the custom-provider re-create literal inprovider_tui.goeach get the one extra field. (Side finding while auditing this:cloneProviderEntryalready dropsExtraHeaderstoday — pre-existing, we can file/fix that separately.)3. Backward compatibility — guarantees
api_keyconfigs: byte-for-byte unchanged behavior (static key short-circuits before any command logic).ANTHROPIC_API_KEY,OCR_LLM_TOKEN, CCANTHROPIC_BASE_URL/ANTHROPIC_AUTH_TOKEN, …): unchanged — the new source slots between static config and env fallback, and is inert unless the user sets it.api_keyandapi_key_cmdset → static wins + one stderr warning (documented above).llmsection gets a matchingauth_token_cmd(droppable from v1 if you'd rather not extend the legacy path). Gate pinned precisely: the legacy branch falls through to the CC-env fallback only whenauth_token == "" && auth_token_cmd == ""; an incomplete legacy config (e.g. nourl) still falls through without ever executing the command; a set-but-failingauth_token_cmdon a complete legacy config is a hard error, not a fall-through.omitempty— untouched configs don't change on rewrite.cmd /Carm compiles under its build tag and mirrors the Unix logic, but CI runs Linux only — stating plainly that the Windows path ships compile-checked but not CI-tested.4. Config examples
Before:
{ "provider": "anthropic", "providers": { "anthropic": { "api_key": "sk-ant-xxxx", "model": "claude-sonnet-4-6" } }, "custom_providers": { "local": { "url": "http://127.0.0.1:11434/v1", "protocol": "openai", "api_key": "ollama" } }, "llm": { "url": "https://legacy.example/v1", "auth_token": "tok-xxxx" } }After:
{ "provider": "anthropic", "providers": { "anthropic": { "api_key_cmd": "op read op://dev/anthropic/api-key", "model": "claude-sonnet-4-6" } }, "custom_providers": { "local": { "url": "http://127.0.0.1:11434/v1", "protocol": "openai", "api_key_cmd": "pass show ollama-key" } }, "llm": { "url": "https://legacy.example/v1", "auth_token_cmd": "pass show legacy-token" } }Scope
No new dependencies (stdlib
os/execonly), no TUI UI, no caching/daemon, no keyring. ~140 LOC product + ~220 LOC table-driven tests (command runner matrix incl. timeout/empty/multi-line rows via an injected timeout so tests run in <1s; resolution precedence tests reusing the existingclearAllEnv/t.TempDir()conventions), plus a "API key from a command" section in configuration.md (en/zh/ja). Coverage gate: the build-tag split keeps the Windows arm out of the Linux coverage denominator, so the 80% gate holds.If this shape looks right, we'll open the PR against it; happy to trim
auth_token_cmdor anything else you'd rather defer.acoliver commentedon Jul 24, 2026
This is exactly the shape I had in mind. The design is solid — signing off.
A few specific points:
Precedence (static
api_keywins overapi_key_cmd) — Correct. If both are set, static wins with a stderr warning rather than erroring. This matches git'scredential.helperbehavior where the first successful source is used.Hard error on command failure — Correct. A misconfigured
api_key_cmdmust never silently fall back to an env var. The failure mode table is exactly right.60s timeout — Reasonable, matches AWS SDK
credential_process. Pinentry and 1Passwordopprompts can take a few seconds; a shorter timeout would false-fail on legitimate interactive unlock prompts.auth_token_cmdfor the legacyllmsection — Worth including in v1. The gate logic (only execute when legacy config is complete, hard error on failure) is correct. Better to land it now than add a second PR later.Side finding:
cloneProviderEntrydropsExtraHeaders— Worth filing separately; that's a pre-existing bug independent of this work.Windows path — Compile-checked but not CI-tested is fine. Document it in the PR description.
Go ahead and open the PR. Happy to review it when it lands.
feat(config): resolve api_key/auth_token from a command (alibaba#236)
feat(config): resolve api_key/auth_token from a command (alibaba#236)
feat(config): resolve api_key/auth_token from a command (alibaba#236)
feat(config): resolve api_key/auth_token from a command (alibaba#236)
feat(config): resolve api_key/auth_token from a command (#236) (#605)
feat(config): resolve api_key/auth_token from a command (alibaba#236) (…