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.
This commit is contained in:
@@ -1,8 +1,10 @@
|
||||
package cmdutil
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"os"
|
||||
"sync"
|
||||
|
||||
@@ -124,10 +126,12 @@ func buildClient(f *Factory) (*sdk.Client, error) {
|
||||
// Only fetch the secrets the context actually references. Skipping the
|
||||
// unused fetch avoids a `security` exec (macOS) / DBus call (Linux) per
|
||||
// authenticated invocation.
|
||||
var accessToken string
|
||||
if ctx.TokenRef != "" {
|
||||
if access, err := loadSecret(store, ctxName, "access"); err != nil {
|
||||
return nil, err
|
||||
} else if access != "" {
|
||||
accessToken = access
|
||||
opts = append(opts, sdk.WithBearerToken(access))
|
||||
}
|
||||
}
|
||||
@@ -138,6 +142,20 @@ func buildClient(f *Factory) (*sdk.Client, error) {
|
||||
opts = append(opts, sdk.WithAPIKey(apiKey))
|
||||
}
|
||||
}
|
||||
// JWT contexts (have both access + refresh refs) get the transparent
|
||||
// 401-retry transport: on the first 401 from a non-/auth/* endpoint, the
|
||||
// transport reads the stored refresh token, calls /api/v1/auth/refresh,
|
||||
// persists the new pair, and replays the original request with the new
|
||||
// bearer. API-key contexts skip this (no refresh semantic) — a 401 from
|
||||
// them propagates as auth.unauthenticated for the caller to handle.
|
||||
if ctx.TokenRef != "" && ctx.RefreshRef != "" {
|
||||
refreshFn := func(rctx context.Context) (string, error) {
|
||||
return refreshAccessToken(rctx, store, ctx.Host, ctxName)
|
||||
}
|
||||
opts = append(opts, sdk.WithTransport(
|
||||
NewAuthRetryTransport(http.DefaultTransport, accessToken, refreshFn),
|
||||
))
|
||||
}
|
||||
// ctx.TenantID is intentionally NOT injected as X-Tenant-ID. Servers derive
|
||||
// tenant from the credential itself (JWT claim or API key prefix); the
|
||||
// header is only meaningful for explicit cross-tenant switching by users
|
||||
@@ -197,3 +215,12 @@ func loadSecret(store secrets.Store, context, key string) (string, error) {
|
||||
}
|
||||
return v, nil
|
||||
}
|
||||
|
||||
// refreshAccessToken is the closure target injected into AuthRetryTransport's
|
||||
// refreshFn. A fresh SDK Client is built here rather than reusing the one
|
||||
// being constructed — that one is itself wrapped by the transport, which
|
||||
// would recurse on refresh. The refresh endpoint is unauthenticated apart
|
||||
// from the refresh token in the body, so no credential options are needed.
|
||||
func refreshAccessToken(ctx context.Context, store secrets.Store, host, ctxName string) (string, error) {
|
||||
return RefreshAndPersist(ctx, store, sdk.NewClient(host), ctxName)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user