diff --git a/cli/AGENTS.md b/cli/AGENTS.md index c6f7651d..d2332178 100644 --- a/cli/AGENTS.md +++ b/cli/AGENTS.md @@ -179,6 +179,41 @@ wired into the SDK transport (`cli/internal/cmdutil/authretry.go`) with singleflight de-dup, so most callers never need to invoke `auth refresh` explicitly. +### Auth security contract + +- **Credential storage**: OS keychain via `go-keyring` (macOS Keychain, + Windows Credential Manager, freedesktop Secret Service). Falls back to + a 0600 file under `$XDG_CONFIG_HOME/weknora/secrets//` only + when no keyring backend is available. `auth login` prints a stderr + warning at fallback time; `weknora doctor` flags it under + `credential_storage`. +- **`auth login --with-token`**: reads the API key from **stdin**, never + from a flag value (so it never appears in `ps` / shell history). The + key is validated against `/auth/me` **before** being persisted — a + typo / expired / wrong-host key fails fast with + `auth.bad_credential` and nothing is written. +- **No env-var token bypass**: WeKnora does NOT honor a `WEKNORA_TOKEN` + env var as an implicit credential source — by design, to avoid the + process-environment leak surface (`/proc//environ`, `ps -E`, + multi-tenant CI runners). CI / scripts should pipe the key via + `weknora auth login --with-token` into the keyring (or the file + fallback under an isolated `$XDG_CONFIG_HOME`). +- **`auth status` / `auth list`**: never emit token values, in either + human or JSON modes. The `mode` field (`bearer` / `api-key`) signals + which credential class is stored, not the value. +- **`auth token`**: the only command that prints the stored credential. + Stdout has **no trailing newline** so `$(weknora auth token)` is + clean; when stdout is a TTY, a stderr advisory warns the user that + the secret just landed in scrollback, plus an extra note for api-key + mode (long-lived, rotate at the server). +- **`auth refresh` `--json`**: returns only `{context}` — never the new + access or refresh token. Agents that need to verify the new + credential should re-run `auth status` (live `/auth/me` probe). +- **`auth logout`**: local-only — deletes the keyring entry + file + fallback + the context entry in `config.yaml`. **Does NOT revoke + server-side.** For JWT, the issued token stays valid until expiry; + for API keys, rotate them in the server UI. + `search` subtree: `search chunks "" --kb X` for hybrid retrieval; `search kb ""` / `search docs "" --kb X` / `search sessions ""` for client-side substring filtering on the listing endpoints. diff --git a/cli/cmd/auth/auth_test.go b/cli/cmd/auth/auth_test.go index bbbeafc4..36705151 100644 --- a/cli/cmd/auth/auth_test.go +++ b/cli/cmd/auth/auth_test.go @@ -76,7 +76,7 @@ func TestPersistAPIKey_WritesContext(t *testing.T) { Context: "ci", APIKey: "sk-zzz", } - require.NoError(t, persistAPIKey(opts, &cmdutil.JSONOptions{}, f)) + require.NoError(t, persistAPIKey(opts, &cmdutil.JSONOptions{}, f, nil)) v, _ := store.Get("ci", "api_key") assert.Equal(t, "sk-zzz", v) cfg, _ := f.Config() diff --git a/cli/cmd/auth/login.go b/cli/cmd/auth/login.go index e88df816..50ebc36a 100644 --- a/cli/cmd/auth/login.go +++ b/cli/cmd/auth/login.go @@ -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. diff --git a/cli/cmd/auth/login_test.go b/cli/cmd/auth/login_test.go index 474d633b..39503b4c 100644 --- a/cli/cmd/auth/login_test.go +++ b/cli/cmd/auth/login_test.go @@ -2,6 +2,7 @@ package auth import ( "context" + "errors" "strings" "testing" @@ -73,6 +74,10 @@ func TestRunLogin_PasswordMode(t *testing.T) { func TestRunLogin_WithToken(t *testing.T) { iostreams.SetForTest(t) f, store := newTestFactoryWithConfig(t, prompt.AgentPrompter{}) + restore := stubAPIKeyValidator(func(_ context.Context, _, _ string) (*sdk.AuthUser, error) { + return &sdk.AuthUser{ID: "u1", Email: "ci@example.com", TenantID: 7}, nil + }) + defer restore() opts := &LoginOptions{ Host: "https://kb.example.com", Context: "ci", @@ -82,11 +87,50 @@ func TestRunLogin_WithToken(t *testing.T) { require.NoError(t, runLogin(context.Background(), opts, nil, f, nil)) got, _ := store.Get("ci", "api_key") assert.Equal(t, "sk-1234", got) + cfg, _ := f.Config() + assert.Equal(t, "ci@example.com", cfg.Contexts["ci"].User, "validator-returned user should be persisted") + assert.Equal(t, uint64(7), cfg.Contexts["ci"].TenantID) +} + +func TestRunLogin_WithToken_ServerRejects(t *testing.T) { + iostreams.SetForTest(t) + f, _ := newTestFactoryWithConfig(t, prompt.AgentPrompter{}) + restore := stubAPIKeyValidator(func(_ context.Context, _, _ string) (*sdk.AuthUser, error) { + return nil, errors.New("HTTP 401: invalid api key") + }) + defer restore() + opts := &LoginOptions{ + Host: "https://kb.example.com", + Context: "ci", + WithToken: true, + StdinReader: strings.NewReader("sk-bad"), + } + err := runLogin(context.Background(), opts, nil, f, nil) + require.Error(t, err) + var typed *cmdutil.Error + require.ErrorAs(t, err, &typed) + assert.Equal(t, cmdutil.CodeAuthBadCredential, typed.Code, + "server-side rejection must surface as auth.bad_credential, not persist the key") +} + +// stubAPIKeyValidator swaps defaultAPIKeyValidator for the test and returns +// a restore func to defer. +func stubAPIKeyValidator(fn apiKeyValidator) func() { + saved := defaultAPIKeyValidator + defaultAPIKeyValidator = fn + return func() { defaultAPIKeyValidator = saved } } func TestRunLogin_WithToken_Empty(t *testing.T) { iostreams.SetForTest(t) f, _ := newTestFactoryWithConfig(t, prompt.AgentPrompter{}) + // Validator must NOT be called when stdin is empty — verify by setting + // a panic-on-call sentinel. + restore := stubAPIKeyValidator(func(_ context.Context, _, _ string) (*sdk.AuthUser, error) { + t.Fatal("validator should not be called on empty stdin") + return nil, nil + }) + defer restore() opts := &LoginOptions{ Host: "https://kb.example.com", Context: "ci",