Skip to content

Support OS keyring auth for local LLM credentials #236

Closed

Description

@acoliver

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:

  1. Explicit CLI option.
  2. Named keyring credential.
  3. Existing config value.
  4. 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:

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 历史记录或暴露在进程列表中。配置中可以引用一个命名凭据,而不是直接保存密钥明文。运行时的认证解析可以采用以下优先级:

  1. 显式 CLI 参数。
  2. 命名的 keyring 凭据。
  3. 现有配置值。
  4. 环境变量回退。

设计建议

  • 尽量使用跨平台 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

  1. lizhengfeng101 commented on Jun 29, 2026

    @lizhengfeng101
    Contributor

    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:

    1. Added complexity for users — A new ocr auth key subcommand 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.

    2. 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.

    3. Existing ecosystem solutions — Most developers already have access to excellent secret management tools that integrate seamlessly with environment variables:

      # 1Password CLI
      export OCR_LLM_AUTH_TOKEN=$(op read "op://vault/ocr/token")
      
      # macOS Keychain (built-in, no extra install)
      export OCR_LLM_AUTH_TOKEN=$(security find-generic-password -s "ocr-token" -w)
      
      # pass (Linux/macOS)
      export OCR_LLM_AUTH_TOKEN=$(pass show ocr/token)
      
      # Bitwarden CLI
      export OCR_LLM_AUTH_TOKEN=$(bw get password ocr-token)

      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! 🙏

  2. acoliver commented on Jun 29, 2026

    @acoliver
    ContributorAuthor

    @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:

    • Docker's Compose docs: "Environment variables are often available to all processes... and can also be printed in logs when debugging errors without your knowledge." Swarm secrets were deliberately built to avoid env vars: "a conscious decision, because environment variables can unintentionally be leaked between containers."
    • Red Hat/OpenShift: env-stored secrets are exposed via "the env command or inspecting the /proc/self/environ file," 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:

    today (leaks to env) with 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 -w
    export …=$(pass show ocr/token) api_key_cmd: pass show ocr/token
    export …=$(bw get password ocr-token) api_key_cmd: bw get password ocr-token

    One 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.

  3. lizhengfeng101 commented on Jun 30, 2026

    @lizhengfeng101
    Contributor

    @acoliver — Great follow-up. We agree that api_key_cmd is a much better scoping than the original keyring proposal. The credential-command pattern is well-established (git credential.helper, AWS credential_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 does api_key_cmd sit in the precedence chain relative to api_key and 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:

    • First-time setup via ocr config set
    • Migrating from an existing api_key to api_key_cmd
    • What about the ocr provider interactive 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.:

    • Existing api_key in config continues to work as-is
    • Existing env-var workflows (ANTHROPIC_API_KEY, OCR_LLM_TOKEN, etc.) are unchanged
    • What if both api_key and api_key_cmd are present — which wins, or is that an error?
    • The legacy llm.auth_token field — does it also get a corresponding auth_token_cmd?

    4. Config examples

    A before/after config.json showing preset providers, custom providers, and the legacy llm section 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!

  4. chethanuk commented on Jul 17, 2026

    @chethanuk
    Contributor

    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 and custom_providers behave identically):

    Priority Source Today After
    1 static api_key in config ✅ ✅ unchanged — static always wins; if both api_key and api_key_cmd are 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)
    2 api_key_cmd (new) — runs the command, uses trimmed stdout as the key
    3 preset env var (ANTHROPIC_API_KEY, DASHSCOPE_API_KEY, …) ✅ ✅ unchanged (custom providers have no env fallback today; that stays true)
    4 none error same error, message extended to mention api_key_cmd

    Command 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 existing cmd/opencodereview/shell_unix.go / shell_windows.go convention). exec.CommandContext with a 60-second timeout (same default as AWS SDK credential_process). The child's stderr passes through to OCR's stderr, so pinentry/1Password/op prompts stay visible. Stdout is TrimSpaced 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):

    Failure Behavior
    non-zero exit error: api_key_cmd for provider "x" failed: exit status 3
    command not found (127) same, with the shell's not-found message visible on stderr
    empty / whitespace-only stdout error: api_key_cmd for provider "x" produced empty output
    multi-line stdout error (likely a mispasted script; refuse to guess which line is the key)
    timeout (60s) error naming the timeout

    No caching, by design: endpoint resolution runs once per process invocation, so the command (and any pinentry prompt) fires at most once per ocr run. 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:

    ocr config set providers.anthropic.api_key_cmd "op read op://dev/anthropic/api-key"
    # or: pass show anthropic-api-key | head -1
    ocr llm test   # verifies the command runs and the key works

    Migration from an existing api_key:

    ocr config set providers.anthropic.api_key_cmd "pass show anthropic-api-key"
    ocr config set providers.anthropic.api_key ""    # remove the static key; until then static wins + stderr warning

    ocr config set prints the command unmasked — deliberately: the value is a command line, not a secret (the existing masking correctly keys off api_key/auth_token suffixes and won't match api_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 configured api_key_cmd: cloneProviderEntry and the custom-provider re-create literal in provider_tui.go each get the one extra field. (Side finding while auditing this: cloneProviderEntry already drops ExtraHeaders today — pre-existing, we can file/fix that separately.)

    3. Backward compatibility — guarantees

    • Existing api_key configs: byte-for-byte unchanged behavior (static key short-circuits before any command logic).
    • Existing env-var workflows (ANTHROPIC_API_KEY, OCR_LLM_TOKEN, CC ANTHROPIC_BASE_URL/ANTHROPIC_AUTH_TOKEN, …): unchanged — the new source slots between static config and env fallback, and is inert unless the user sets it.
    • Both api_key and api_key_cmd set → static wins + one stderr warning (documented above).
    • Legacy llm section gets a matching auth_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 when auth_token == "" && auth_token_cmd == ""; an incomplete legacy config (e.g. no url) still falls through without ever executing the command; a set-but-failing auth_token_cmd on a complete legacy config is a hard error, not a fall-through.
    • New JSON fields are omitempty — untouched configs don't change on rewrite.
    • Windows: the cmd /C arm 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/exec only), 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 existing clearAllEnv/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_cmd or anything else you'd rather defer.

  5. acoliver commented on Jul 24, 2026

    @acoliver
    ContributorAuthor

    This is exactly the shape I had in mind. The design is solid — signing off.

    A few specific points:

    1. Precedence (static api_key wins over api_key_cmd) — Correct. If both are set, static wins with a stderr warning rather than erroring. This matches git's credential.helper behavior where the first successful source is used.

    2. Hard error on command failure — Correct. A misconfigured api_key_cmd must never silently fall back to an env var. The failure mode table is exactly right.

    3. 60s timeout — Reasonable, matches AWS SDK credential_process. Pinentry and 1Password op prompts can take a few seconds; a shorter timeout would false-fail on legitimate interactive unlock prompts.

    4. auth_token_cmd for the legacy llm section — 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.

    5. Side finding: cloneProviderEntry drops ExtraHeaders — Worth filing separately; that's a pre-existing bug independent of this work.

    6. 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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions