Files
Enterprise-Knowledge-Base/cli/cmd/auth/refresh.go
T
nullkey 4c26bc9ecc feat(cli): auth refresh + transparent 401 retry transport
Two halves of v0.3 roadmap item 3-2.

(1) `weknora auth refresh` — explicit token renewal:
Reads the stored refresh_token, spends it via POST /api/v1/auth/refresh
(OAuth refresh-token grant), and persists both new tokens. API-key
contexts rejected with input.invalid_argument (no refresh semantic).

NOTE: gh CLI has `gh auth refresh` but with different semantics —
gh's variant is an OAuth scope expansion / re-prompt via the browser
(verified against the gh manual). The two share a name but solve
different problems; there's no direct gh parallel for refresh-token
grant because gh's PAT/OAuth-app model doesn't expose a short-lived
access_token + refresh_token pair to clients.

Error mapping:
- no current context → auth.unauthenticated
- --name unknown → local.context_not_found
- missing refresh in keyring → auth.token_expired (hint: re-login)
- server Success=false → auth.token_expired
- network → network.error
Envelope omits the token values (would leak into agent transcripts).

(2) AuthRetryTransport — transparent retry:
Wraps the SDK http.Client. On a 401 from a non-/auth/* endpoint:
- JWT context: read refresh token, hit /auth/refresh, persist new pair,
  replay original request with new bearer.
- API-key context: pass through (no refresh semantic).
- Non-replayable body (req.GetBody == nil): pass through.
- /auth/login or /auth/refresh: pass through (no recursion).
Concurrent 401s are singleflight-coalesced via sync.Mutex — 5 parallel
calls trigger exactly 1 refresh.

SDK additions (additive, non-breaking):
- WithTransport(rt http.RoundTripper) ClientOption.
- PathAuthLogin / PathAuthRefresh constants (cli/internal/cmdutil/authretry
  imports them so the CLI and SDK can't drift on path strings).

Refactor surfaced by the post-commit reviewer round:
- cmdutil.RefreshAndPersist(ctx, store, refresher, ctxName) — the
  load-refresh → call-SDK → persist-pair sequence was duplicated between
  the standalone `auth refresh` and the transport's refresh closure;
  collapsed to one canonical implementation.
- refreshFn signature takes context.Context so Ctrl+C during a
  transparent refresh cancels.
- AuthRetryTransport.CurrentToken() removed — never called.

8 + 8 + 8 unit tests cover happy path / refresh-fail / auth-endpoint
skip / api-key passthrough / singleflight under concurrency / non-
replayable-body fallback.

Roadmap: 3-2.
2026-05-14 10:57:17 +08:00

120 lines
4.4 KiB
Go

package auth
import (
"context"
"fmt"
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/agent"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/format"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
sdk "github.com/Tencent/WeKnora/client"
)
// RefreshOptions captures `weknora auth refresh` flag state.
type RefreshOptions struct {
Name string // --name: target context (defaults to current)
JSONOut bool
}
// refreshResult is the typed payload emitted under data on success. Token
// values are intentionally NOT included — emitting them would leak secrets
// into stdout / agent transcripts. Agents needing to verify the new token
// can re-run `weknora auth status` (live API check).
type refreshResult struct {
Context string `json:"context"`
}
// NewCmdRefresh builds `weknora auth refresh`. Renews the JWT access
// token by spending the stored refresh_token via POST /auth/refresh —
// the standard OAuth refresh-token grant. Note: `gh auth refresh`
// shares the name but has a different semantic (interactive OAuth-
// scope expansion via the browser); there's no direct gh parallel
// because gh's PAT/OAuth-app model doesn't have a short-lived
// access_token + refresh_token pair.
//
// API-key contexts are rejected — they have no refresh semantic;
// rotate the key via the server UI instead.
func NewCmdRefresh(f *cmdutil.Factory) *cobra.Command {
opts := &RefreshOptions{}
cmd := &cobra.Command{
Use: "refresh",
Short: "Renew the JWT access token using the stored refresh token",
Long: `Reads the refresh token previously stored by ` + "`weknora auth login`" + ` and
exchanges it for a new access + refresh token pair via POST /api/v1/auth/refresh.
Both new tokens replace the existing entries in the OS keyring.
API-key contexts are rejected with input.invalid_argument — they have no
refresh semantic. Rotate the key in the server UI instead.`,
Example: ` weknora auth refresh # refresh the current context
weknora auth refresh --name staging # refresh a specific context`,
Args: cobra.NoArgs,
RunE: func(c *cobra.Command, _ []string) error {
return runRefresh(c.Context(), opts, f, defaultRefresher)
},
}
cmd.Flags().StringVar(&opts.Name, "name", "", "Context to refresh (defaults to the current context)")
cmd.Flags().BoolVar(&opts.JSONOut, "json", false, "Output JSON envelope")
agent.SetAgentHelp(cmd, "Renews the access token using the stored refresh token. Errors with auth.token_expired when refresh itself is rejected — surface the hint to re-run auth login.")
return cmd
}
// defaultRefresher constructs a fresh, unauthenticated SDK client targeting
// host — the /auth/refresh endpoint reads the refresh token from the body,
// so no bearer / api-key header is needed.
func defaultRefresher(host string) cmdutil.Refresher {
return sdk.NewClient(host)
}
func runRefresh(ctx context.Context, opts *RefreshOptions, f *cmdutil.Factory, refresherFor func(host string) cmdutil.Refresher) error {
cfg, err := f.Config()
if err != nil {
return err
}
name := opts.Name
if name == "" {
name = cfg.CurrentContext
}
if name == "" {
return cmdutil.NewError(cmdutil.CodeAuthUnauthenticated,
"no current context configured; run `weknora auth login` to set one up")
}
c, ok := cfg.Contexts[name]
if !ok {
return cmdutil.NewError(cmdutil.CodeLocalContextNotFound,
fmt.Sprintf("context not found: %s", name))
}
if c.Host == "" {
return cmdutil.NewError(cmdutil.CodeLocalConfigCorrupt,
fmt.Sprintf("context %q has no host", name))
}
if c.RefreshRef == "" {
hint := "api-key contexts can't be refreshed — rotate the key in the server UI and run `weknora auth login --with-token`"
if c.APIKeyRef == "" {
hint = "no refresh token stored — run `weknora auth login` to authenticate"
}
return &cmdutil.Error{
Code: cmdutil.CodeInputInvalidArgument,
Message: fmt.Sprintf("context %q has no refresh token", name),
Hint: hint,
}
}
store, err := f.Secrets()
if err != nil {
return err
}
if _, err := cmdutil.RefreshAndPersist(ctx, store, refresherFor(c.Host), name); err != nil {
return err
}
if opts.JSONOut {
return format.WriteEnvelope(iostreams.IO.Out,
format.Success(refreshResult{Context: name}, &format.Meta{Context: name}))
}
fmt.Fprintf(iostreams.IO.Out, "✓ Refreshed access token for context %s\n", name)
return nil
}