refactor(cli): auth security audit — gh CLI parity hardening

Compared the auth subtree (login/logout/list/status/refresh/token)
against gh CLI's auth implementation. Three gaps closed:

1. `auth login --with-token` validates the API key against `/auth/me`
   before persisting (mirrors gh's pre-persist GetCurrentLogin probe).
   A typo'd / expired / wrong-host key fails fast with
   `auth.bad_credential` (exit 3) and nothing is written to the
   keyring. Side benefit: api-key contexts now carry the resolved
   `user` + `tenant_id` at rest, so `auth list` reflects who owns
   the key — previously these columns were blank for `--with-token`
   contexts because we never queried the server.

2. `auth login` prints a stderr advisory when the secrets store falls
   back to the 0600 plaintext file (keychain unavailable — typical on
   headless CI, WSL without DBus, agent containers). `weknora doctor`
   carried the same info in its credential_storage check, but users
   who go straight to `auth login` could miss it. gh has the same
   silent-fallback gap; we're stricter here.

3. AGENTS.md adds an "Auth security contract" section documenting:
   - Credential storage (keychain primary, 0600 file fallback)
   - `--with-token` reads stdin (not flag value), pre-validated
   - No env-var token bypass — by design, to avoid the
     `/proc/<pid>/environ` / `ps -E` leak surface that
     `GH_TOKEN`-style env vars expose
   - `auth status` / `auth list` never emit token values
   - `auth refresh --json` returns only `{context}` (never the
     new tokens)
   - `auth token` stdout has no trailing newline + TTY stderr hint
   - `auth logout` is local-only (no server-side revocation)

Verified against gh CLI behavior (cli.github.com manual + cli/cli
trunk source):

| dimension                       | gh             | weknora v0.4 |
|---------------------------------|----------------|--------------|
| pre-persist token validation    | ✓              | ✓ (new)      |
| OS keychain primary             | go-keyring     | go-keyring   |
| stderr warning on file fallback | ✗ silent       | ✓ (new)      |
| `auth status` default token     | masked prefix  | not shown    |
| `auth token` TTY warning        | ✗              | ✓            |
| env-var token bypass            | ✓ (GH_TOKEN)   | ✗ by design  |
| process-args / `ps` leak surface| ✗ stdin only   | ✗ stdin only |
This commit is contained in:
nullkey
2026-05-15 01:51:11 +08:00
committed by lyingbug
parent e623e8208f
commit a0dd989c81
4 changed files with 137 additions and 5 deletions
+57 -4
View File
@@ -12,6 +12,7 @@ import (
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/config"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
"github.com/Tencent/WeKnora/cli/internal/secrets"
sdk "github.com/Tencent/WeKnora/client"
)
@@ -41,6 +42,27 @@ type LoginService interface {
Login(ctx context.Context, req sdk.LoginRequest) (*sdk.LoginResponse, error)
}
// apiKeyValidator probes /auth/me with the supplied API key so a bad key
// fails fast at `auth login --with-token` time rather than on the next
// authenticated call. Mirrors gh CLI's pre-persist token verification.
//
// Returns the resolved user (used to populate context.User / TenantID at
// rest, so later `auth list` reflects who owns the key).
type apiKeyValidator func(ctx context.Context, host, apiKey string) (*sdk.AuthUser, error)
// defaultAPIKeyValidator builds a one-shot SDK client with the supplied key
// and calls /auth/me. Side-effect-free; no persistence.
var defaultAPIKeyValidator apiKeyValidator = func(ctx context.Context, host, apiKey string) (*sdk.AuthUser, error) {
resp, err := sdk.NewClient(host, sdk.WithAPIKey(apiKey)).GetCurrentUser(ctx)
if err != nil {
return nil, err
}
if !resp.Success || resp.Data.User == nil {
return nil, fmt.Errorf("server rejected the API key (no user returned)")
}
return resp.Data.User, nil
}
// NewCmdLogin builds the `weknora auth login` command. runF is the testable
// entrypoint (left nil for production; see cli/cmd/auth/login_test.go).
func NewCmdLogin(f *cmdutil.Factory, runF func(context.Context, *LoginOptions, *cmdutil.JSONOptions, *cmdutil.Factory, LoginService) error) *cobra.Command {
@@ -102,7 +124,14 @@ func runLogin(ctx context.Context, opts *LoginOptions, jopts *cmdutil.JSONOption
return cmdutil.NewError(cmdutil.CodeInputMissingFlag, "--with-token requires an API key piped to stdin")
}
opts.APIKey = key
return persistAPIKey(opts, jopts, f)
// Validate against the server before persisting so a typo'd /
// expired / wrong-host key fails fast (gh CLI parity). The probe
// is /auth/me — read-only, side-effect-free.
user, err := defaultAPIKeyValidator(ctx, opts.Host, key)
if err != nil {
return cmdutil.Wrapf(cmdutil.CodeAuthBadCredential, err, "validate API key")
}
return persistAPIKey(opts, jopts, f, user)
}
// Interactive: prompt for email + password.
@@ -139,18 +168,27 @@ func runLogin(ctx context.Context, opts *LoginOptions, jopts *cmdutil.JSONOption
}
// persistAPIKey saves the --with-token API key and writes the context.
func persistAPIKey(opts *LoginOptions, jopts *cmdutil.JSONOptions, f *cmdutil.Factory) error {
// user is the principal returned by /auth/me during pre-persist validation,
// used to populate context.User / TenantID so `auth list` reflects who
// owns the key.
func persistAPIKey(opts *LoginOptions, jopts *cmdutil.JSONOptions, f *cmdutil.Factory, user *sdk.AuthUser) error {
store, err := f.Secrets()
if err != nil {
return err
}
warnOnFileFallback(store)
if err := store.Set(opts.Context, "api_key", opts.APIKey); err != nil {
return cmdutil.Wrapf(cmdutil.CodeLocalKeychainDenied, err, "save api key")
}
return saveContextRef(opts, jopts, f, &config.Context{
ctx := &config.Context{
Host: opts.Host,
APIKeyRef: store.Ref(opts.Context, "api_key"),
}, nil)
}
if user != nil {
ctx.User = user.Email
ctx.TenantID = user.TenantID
}
return saveContextRef(opts, jopts, f, ctx, user)
}
// persistJWT saves access + refresh tokens and writes the context.
@@ -159,6 +197,7 @@ func persistJWT(opts *LoginOptions, jopts *cmdutil.JSONOptions, f *cmdutil.Facto
if err != nil {
return err
}
warnOnFileFallback(store)
if err := store.Set(opts.Context, "access", resp.Token); err != nil {
return cmdutil.Wrapf(cmdutil.CodeLocalKeychainDenied, err, "save access token")
}
@@ -227,6 +266,20 @@ func validateHost(host string) error {
return err
}
// warnOnFileFallback prints a one-shot stderr advisory when the secrets
// store fell back to the plaintext 0600 file backend (keychain unavailable
// — typical on headless CI, WSL without DBus, agent containers). Helps
// users notice that credentials are NOT in the OS keychain before they're
// surprised by it later. doctor's credential_storage check carries the
// same info but agents that bypass doctor would otherwise miss it.
func warnOnFileFallback(store secrets.Store) {
if _, isFile := store.(*secrets.FileStore); !isFile {
return
}
fmt.Fprintln(iostreams.IO.Err, "warning: OS keychain unavailable — credentials will be saved to a 0600 file under $XDG_CONFIG_HOME/weknora/secrets/.")
fmt.Fprintln(iostreams.IO.Err, " install / unlock the keyring (or use `weknora doctor` to inspect) for OS-backed storage.")
}
// readStdinTrimmed reads all of r and returns the result with surrounding
// whitespace stripped. Empty result is returned as-is for the caller to
// validate.