refactor(cli): envelope sweep — Emit shape, batch ops, MCP StructuredContent, api flag cleanup

Sweep every CLI output path through the v0.7 envelope contract.

FormatOptions.Emit signature changes to (w, data, meta *output.Meta)
so list commands surface meta.count / has_more in the wire envelope.
TTY indent decision plumbed via FormatOptions.TTY (set by
ResolveDefault). --format and --jq promoted to persistent root flags
so unknown-subcommand paths still reach the typed-envelope guard
(per-command registration would have rejected --format on unknown
commands as cobra-prose exit 2). WEKNORA_FORMAT env-var fallback
honored before TTY-resolved default. AddFormatFlag retained for the
per-command --jq field-hint Long-text addendum.

~55 production Emit call sites swept across cli/cmd/**: list paths
populate meta.count; mutation paths pass nil meta; envelope.profile
threaded via globalProfile. Existing JSON-shape tests migrated to
decode the envelope wrapper.

Multi-target batch operations get a unified shape via new helpers:
- output.BatchItem + output.WriteBatchEnvelope (§4.5 per-item ok
  pattern; data:[{id, ok, result?|error?}], meta:{count, successes*,
  failures*}; Successes/Failures *int so explicit zero survives
  omitempty in all-fail case).
- cmdutil.RunBatch + cmdutil.EmitBatch + cmdutil.DeletedAtNow +
  cmdutil.ClassifyContextErr collapse the three previously-duplicated
  multi-delete pipelines (doc / chunk / session) into one call site
  pattern. doc upload --recursive uses the same helpers with a per-
  file resultFn. Summary error sets Silent:true so the stderr
  envelope path doesn't duplicate the stdout batch detail (exit 1
  preserved via Code → ExitCode).

ConfirmDestructive / ConfirmDestructiveBatch extended with action +
retryCmd parameters. Every destructive command (kb delete, kb edit,
doc delete, doc delete --all, agent delete, agent edit, session
delete, chunk delete, auth logout, api -X DELETE) now attaches
error.risk.{level:"destructive", action:"<noun.verb>"} +
error.retry_command on the exit-10 envelope. kb edit / agent edit
also gain the destructive guard wiring (CHANGELOG listed them as
gated but they were silently executing without -y).

MCP tool handlers' 31 error paths return CallToolResult with
IsError + Content text fallback + StructuredContent (envelope.error
shape via cmdutil.ErrorToDetail). Handler Out type changed from
typed *sdk.X to any so the go-sdk auto-marshal doesn't overwrite
StructuredContent with a zero-struct on error returns. Success path
manually populates CallToolResult.StructuredContent via successResult
helper.

weknora api cleanup:
- -d/--data flag removed; body via --input <file> or --input -
  (stdin) only. Aligns with gh / curl convention.
- HTTP method whitelist removed; any non-empty method accepted.
- HTTP Retry-After header → cmdutil.Error.RetryAfterSeconds →
  envelope.error.retry_after_seconds.
- runAPIPaginated raw-passthrough fallback now wraps response in
  envelope so --paginate never emits bare JSON to stdout.

Test sweep: ~60 cmd/** tests migrated to decode envelope shape.
9 wire-contract goldens updated under cli/acceptance/testdata/wire/.

Spec: docs/superpowers/specs/2026-05-20-weknora-cli-v0.7-design.md §4 / §5
This commit is contained in:
nullkey
2026-05-21 18:41:56 +08:00
committed by lyingbug
parent 733bb3aaa1
commit ad150c7126
96 changed files with 2354 additions and 864 deletions
+1 -8
View File
@@ -39,14 +39,7 @@ func modeFromRefs(apiKeyRef, tokenRef string) string {
func NewCmdAuth(f *cmdutil.Factory) *cobra.Command {
cmd := &cobra.Command{
Use: "auth",
Short: "Manage authentication credentials and contexts",
// NoArgs makes cobra emit its canonical `unknown command "X" for
// "weknora auth"` for any positional, which mapCobraError tags as
// FlagError → exit 2. Run (not RunE) is required: a parent with
// neither Run nor RunE short-circuits to help and skips Args
// validation entirely.
Args: cobra.NoArgs,
Run: func(c *cobra.Command, _ []string) { _ = c.Help() },
Short: "Manage authentication credentials and profiles",
}
cmd.AddCommand(NewCmdLogin(f, nil))
cmd.AddCommand(NewCmdLogout(f))
+6 -5
View File
@@ -31,12 +31,13 @@ func TestNewCmdAuth_TreeShape(t *testing.T) {
func TestNewCmdLogin_FlagsRegistered(t *testing.T) {
cmd := NewCmdLogin(&cmdutil.Factory{}, nil)
for _, name := range []string{"host", "name", "with-token", "format"} {
// --format is a persistent root flag (v0.7); only per-command flags here.
for _, name := range []string{"host", "name", "with-token"} {
assert.NotNilf(t, cmd.Flags().Lookup(name), "flag %s missing", name)
}
// `--context` should NOT be a local flag (it's the global persistent flag).
// Local registration would silently shadow the global single-shot override.
assert.Nil(t, cmd.Flags().Lookup("context"), "auth login must not declare a local --context flag (use --name)")
// --profile is the global persistent override; local registration would
// silently shadow it.
assert.Nil(t, cmd.Flags().Lookup("profile"), "auth login must not declare a local --profile flag (use --name)")
}
func TestNewCmdLogin_InvokesRunF(t *testing.T) {
@@ -76,7 +77,7 @@ func TestPersistAPIKey_WritesContext(t *testing.T) {
Context: "ci",
APIKey: "sk-zzz",
}
require.NoError(t, persistAPIKey(opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, nil))
require.NoError(t, persistAPIKey(opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, f, nil))
v, _ := store.Get("ci", "api_key")
assert.Equal(t, "sk-zzz", v)
cfg, _ := f.Config()
+7 -5
View File
@@ -10,6 +10,7 @@ import (
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/format"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
"github.com/Tencent/WeKnora/cli/internal/output"
)
type ListOptions struct{}
@@ -29,13 +30,13 @@ type listEntry struct {
}
// NewCmdList builds `weknora auth list`. Per-host enumeration: render one
// row per registered context, marking the active one. Reads only
// row per registered profile, marking the active one. Reads only
// ~/.config/weknora/config.yaml - no network, no keyring touch.
func NewCmdList(f *cmdutil.Factory) *cobra.Command {
cmd := &cobra.Command{
Use: "list",
Short: "List configured authentication contexts",
Long: `Show every configured context (name, host, user, mode, current). Read-only; no network or keyring access.`,
Short: "List configured authentication profiles",
Long: `Show every configured profile (name, host, user, mode, current). Read-only; no network or keyring access.`,
Args: cobra.NoArgs,
RunE: func(c *cobra.Command, _ []string) error {
fopts, err := cmdutil.CheckFormatFlag(c)
@@ -68,10 +69,11 @@ func runList(fopts *cmdutil.FormatOptions, f *cmdutil.Factory) error {
sort.Slice(entries, func(i, j int) bool { return entries[i].Name < entries[j].Name })
if fopts.WantsJSON() {
return fopts.Emit(iostreams.IO.Out, entries)
meta := &output.Meta{Count: len(entries)}
return fopts.Emit(iostreams.IO.Out, entries, meta)
}
if len(entries) == 0 {
fmt.Fprintln(iostreams.IO.Out, "No contexts configured. Run `weknora auth login` to create one.")
fmt.Fprintln(iostreams.IO.Out, "No profiles configured. Run `weknora auth login` to create one.")
return nil
}
tw := tabwriter.NewWriter(iostreams.IO.Out, 0, 0, 2, ' ', 0)
+10 -5
View File
@@ -28,7 +28,7 @@ func TestList_HumanRender(t *testing.T) {
"staging": {Host: "https://staging", APIKeyRef: "keychain://staging/api_key"},
},
}
require.NoError(t, runList(&cmdutil.FormatOptions{Mode: cmdutil.FormatText}, newListFactory(cfg)))
require.NoError(t, runList(&cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, newListFactory(cfg)))
got := out.String()
// One row per context, current marked with `*`.
@@ -44,8 +44,8 @@ func TestList_HumanRender(t *testing.T) {
func TestList_Empty(t *testing.T) {
out, _ := iostreams.SetForTest(t)
require.NoError(t, runList(&cmdutil.FormatOptions{Mode: cmdutil.FormatText}, newListFactory(&config.Config{})))
assert.Contains(t, out.String(), "No contexts configured")
require.NoError(t, runList(&cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, newListFactory(&config.Config{})))
assert.Contains(t, out.String(), "No profiles configured")
}
func TestList_JSON_BareArray(t *testing.T) {
@@ -59,8 +59,13 @@ func TestList_JSON_BareArray(t *testing.T) {
}
require.NoError(t, runList(&cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, newListFactory(cfg)))
var got []listEntry
require.NoError(t, json.Unmarshal(out.Bytes(), &got))
var env struct {
OK bool `json:"ok"`
Data []listEntry `json:"data"`
}
require.NoError(t, json.Unmarshal(out.Bytes(), &env))
assert.True(t, env.OK)
got := env.Data
require.Len(t, got, 2)
// Sorted: prod < staging.
assert.Equal(t, "prod", got[0].Name)
+18 -5
View File
@@ -20,7 +20,7 @@ import (
// keyring; agents who need to verify the credential should re-run
// `auth status`.
var authLoginFields = []string{
"context", "host", "mode", "user", "tenant_id",
"profile", "host", "mode", "user", "tenant_id",
}
// LoginOptions is the configuration captured from flags + prompts.
@@ -93,7 +93,7 @@ the current_context in ~/.config/weknora/config.yaml.`,
},
}
cmd.Flags().StringVar(&opts.Host, "host", "", "WeKnora server URL, e.g. https://kb.example.com")
cmd.Flags().StringVar(&opts.Context, "name", "default", "Context name to register in config.yaml")
cmd.Flags().StringVar(&opts.Context, "name", "default", "Profile name to register in config.yaml")
cmd.Flags().BoolVar(&opts.WithToken, "with-token", false, "Read an API key from stdin instead of prompting for password")
cmdutil.AddFormatFlag(cmd, authLoginFields...)
_ = cmd.MarkFlagRequired("host")
@@ -128,6 +128,13 @@ func runLogin(ctx context.Context, opts *LoginOptions, fopts *cmdutil.FormatOpti
// is /auth/me - read-only, side-effect-free.
user, err := defaultAPIKeyValidator(ctx, opts.Host, key)
if err != nil {
// Transport errors (connection refused, DNS failure) must not be
// surfaced as auth.bad_credential — the key may be fine but the
// host is unreachable. Classify via WrapHTTP so network errors
// get CodeNetworkError and the hint points at `weknora doctor`.
if cmdutil.ClassifyHTTPError(err) == cmdutil.CodeNetworkError {
return cmdutil.Wrapf(cmdutil.CodeNetworkError, err, "validate API key: check host reachability")
}
return cmdutil.Wrapf(cmdutil.CodeAuthBadCredential, err, "validate API key")
}
return persistAPIKey(opts, fopts, f, user)
@@ -157,6 +164,12 @@ func runLogin(ctx context.Context, opts *LoginOptions, fopts *cmdutil.FormatOpti
resp, err := svc.Login(ctx, sdk.LoginRequest{Email: opts.Email, Password: opts.Password})
if err != nil {
// Transport errors (connection refused, DNS failure) must not be
// surfaced as auth.bad_credential — credentials may be fine but the
// host is unreachable. Classify so network errors get CodeNetworkError.
if cmdutil.ClassifyHTTPError(err) == cmdutil.CodeNetworkError {
return cmdutil.Wrapf(cmdutil.CodeNetworkError, err, "login: check host reachability")
}
return cmdutil.Wrapf(cmdutil.CodeAuthBadCredential, err, "login")
}
if !resp.Success || resp.Token == "" {
@@ -220,7 +233,7 @@ func persistJWT(opts *LoginOptions, fopts *cmdutil.FormatOptions, f *cmdutil.Fac
// loginResult is the typed payload emitted by `--format json`. mode is derived from
// whether the server returned a user (password flow) vs API-key flow.
type loginResult struct {
Context string `json:"context"`
Profile string `json:"profile"`
Host string `json:"host"`
Mode string `json:"mode"` // ModeBearer or ModeAPIKey
User string `json:"user,omitempty"`
@@ -242,13 +255,13 @@ func saveContextRef(opts *LoginOptions, fopts *cmdutil.FormatOptions, f *cmdutil
return cmdutil.Wrapf(cmdutil.CodeLocalFileIO, err, "save config")
}
if fopts.WantsJSON() {
result := loginResult{Context: opts.Context, Host: opts.Host, Mode: ModeAPIKey}
result := loginResult{Profile: opts.Context, Host: opts.Host, Mode: ModeAPIKey}
if user != nil {
result.Mode = ModeBearer
result.User = user.Email
result.TenantID = user.TenantID
}
return fopts.Emit(iostreams.IO.Out, result)
return fopts.Emit(iostreams.IO.Out, result, nil)
}
who := opts.Context
if user != nil {
+9 -7
View File
@@ -62,7 +62,7 @@ func TestRunLogin_PasswordMode(t *testing.T) {
Host: "https://kb.example.com",
Context: "prod",
}
require.NoError(t, runLogin(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, svc))
require.NoError(t, runLogin(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, f, svc))
assert.Equal(t, "a@b.c", svc.got.email)
assert.Equal(t, "secret", svc.got.password)
@@ -84,7 +84,7 @@ func TestRunLogin_WithToken(t *testing.T) {
WithToken: true,
StdinReader: strings.NewReader(" sk-1234 \n"),
}
require.NoError(t, runLogin(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, nil))
require.NoError(t, runLogin(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, f, nil))
got, _ := store.Get("ci", "api_key")
assert.Equal(t, "sk-1234", got)
cfg, _ := f.Config()
@@ -96,7 +96,9 @@ 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")
// Use the SDK-format HTTP error message so ClassifyHTTPError detects
// this as an HTTP 401, not a transport/network failure.
return nil, errors.New("HTTP error 401: invalid api key")
})
defer restore()
opts := &LoginOptions{
@@ -105,7 +107,7 @@ func TestRunLogin_WithToken_ServerRejects(t *testing.T) {
WithToken: true,
StdinReader: strings.NewReader("sk-bad"),
}
err := runLogin(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, nil)
err := runLogin(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, f, nil)
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
@@ -137,7 +139,7 @@ func TestRunLogin_WithToken_Empty(t *testing.T) {
WithToken: true,
StdinReader: strings.NewReader(""),
}
err := runLogin(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, nil)
err := runLogin(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, f, nil)
require.Error(t, err)
assert.Contains(t, err.Error(), "input.missing_flag")
}
@@ -145,7 +147,7 @@ func TestRunLogin_WithToken_Empty(t *testing.T) {
func TestRunLogin_BadHost(t *testing.T) {
iostreams.SetForTest(t)
f, _ := newTestFactoryWithConfig(t, prompt.AgentPrompter{})
err := runLogin(context.Background(), &LoginOptions{Host: "ftp://nope"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, nil)
err := runLogin(context.Background(), &LoginOptions{Host: "ftp://nope"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, f, nil)
require.Error(t, err)
assert.Contains(t, err.Error(), "input.invalid_argument")
}
@@ -154,7 +156,7 @@ func TestRunLogin_LoginRefused(t *testing.T) {
iostreams.SetForTest(t)
f, _ := newTestFactoryWithConfig(t, scriptedPrompter{email: "a@b.c", password: "x"})
svc := &fakeLoginService{resp: &sdk.LoginResponse{Success: false, Message: "bad password"}}
err := runLogin(context.Background(), &LoginOptions{Host: "https://x", Context: "p"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, svc)
err := runLogin(context.Background(), &LoginOptions{Host: "https://x", Context: "p"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, f, svc)
require.Error(t, err)
assert.Contains(t, err.Error(), "auth.bad_credential")
}
+44 -19
View File
@@ -13,12 +13,13 @@ import (
)
type LogoutOptions struct {
Name string // --name: target a specific context (default: current)
All bool // --all: clear every context
Name string // --name: target a specific profile (default: current)
All bool // --all: clear every profile
Yes bool // sourced from the global -y/--yes persistent flag
}
// authLogoutFields enumerates the fields surfaced for `--format json` discovery
// on `auth logout`. The result is the list of context names that were
// on `auth logout`. The result is the list of profile names that were
// logged out.
var authLogoutFields = []string{"removed"}
@@ -28,21 +29,21 @@ type logoutResult struct {
}
// NewCmdLogout builds `weknora auth logout`. Clears stored credentials
// (keyring + file fallback) and removes the context entry from config.yaml.
// (keyring + file fallback) and removes the profile entry from config.yaml.
// No server-side revocation - local-only credential clear.
func NewCmdLogout(f *cmdutil.Factory) *cobra.Command {
opts := &LogoutOptions{}
cmd := &cobra.Command{
Use: "logout",
Short: "Remove stored credentials for a context",
Long: `Clear keyring + file-fallback secrets for one context (or all of
them with --all) and drop the context entry from ~/.config/weknora/config.yaml.
Short: "Remove stored credentials for a profile",
Long: `Clear keyring + file-fallback secrets for one profile (or all of
them with --all) and drop the profile entry from ~/.config/weknora/config.yaml.
Note: this does NOT revoke the credential server-side - for API keys, you
must rotate them in the server UI; for JWT, the token will continue to be
accepted until it expires.`,
Example: ` weknora auth logout # current context
weknora auth logout --name staging # specific context
Example: ` weknora auth logout # current profile
weknora auth logout --name staging # specific profile
weknora auth logout --all`,
Args: cobra.NoArgs,
RunE: func(c *cobra.Command, _ []string) error {
@@ -51,13 +52,25 @@ accepted until it expires.`,
return err
}
fopts.ResolveDefault(iostreams.IO.IsStdoutTTY())
opts.Yes, _ = c.Flags().GetBool("yes")
return runLogout(opts, fopts, f)
},
}
cmd.Flags().StringVar(&opts.Name, "name", "", "Context to log out (defaults to the current context)")
cmd.Flags().BoolVar(&opts.All, "all", false, "Log out of every configured context")
cmd.Flags().StringVar(&opts.Name, "name", "", "Profile to log out (defaults to the current profile)")
cmd.Flags().BoolVar(&opts.All, "all", false, "Log out of every configured profile")
cmdutil.AddFormatFlag(cmd, authLogoutFields...)
cmd.MarkFlagsMutuallyExclusive("name", "all")
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
UsedFor: "clear stored credentials for one profile (or all) and remove the profile from config",
Examples: []string{
"weknora auth logout",
"weknora auth logout --name staging",
"weknora auth logout --all",
},
Warnings: []string{
"auth logout drops stored credentials. The user will need to re-authenticate. Confirm scope before invoking.",
},
})
return cmd
}
@@ -67,7 +80,7 @@ func runLogout(opts *LogoutOptions, fopts *cmdutil.FormatOptions, f *cmdutil.Fac
return err
}
if len(cfg.Contexts) == 0 {
return cmdutil.NewError(cmdutil.CodeAuthUnauthenticated, "no contexts configured; nothing to log out")
return cmdutil.NewError(cmdutil.CodeAuthUnauthenticated, "no profiles configured; nothing to log out")
}
targets, err := pickLogoutTargets(opts, cfg)
@@ -75,6 +88,18 @@ func runLogout(opts *LogoutOptions, fopts *cmdutil.FormatOptions, f *cmdutil.Fac
return err
}
// Destructive-write protocol: confirm before clearing credentials.
scope := fmt.Sprintf("%d profile(s) [%s]", len(targets), strings.Join(targets, ", "))
retryCmd := "weknora auth logout -y"
if opts.All {
retryCmd = "weknora auth logout --all -y"
} else if opts.Name != "" {
retryCmd = fmt.Sprintf("weknora auth logout --name %s -y", opts.Name)
}
if err := cmdutil.ConfirmDestructive(f.Prompter(), opts.Yes, fopts.WantsJSON(), "auth credentials", scope, "auth.logout", retryCmd); err != nil {
return err
}
store, err := f.Secrets()
if err != nil {
return err
@@ -95,13 +120,13 @@ func runLogout(opts *LogoutOptions, fopts *cmdutil.FormatOptions, f *cmdutil.Fac
}
if fopts.WantsJSON() {
return fopts.Emit(iostreams.IO.Out, logoutResult{Removed: targets})
return fopts.Emit(iostreams.IO.Out, logoutResult{Removed: targets}, nil)
}
fmt.Fprintf(iostreams.IO.Out, "✓ Logged out of %d context(s): %s\n", len(targets), strings.Join(targets, ", "))
fmt.Fprintf(iostreams.IO.Out, "✓ Logged out of %d profile(s): %s\n", len(targets), strings.Join(targets, ", "))
return nil
}
// pickLogoutTargets resolves the set of contexts to clear from flags + config.
// pickLogoutTargets resolves the set of profiles to clear from flags + config.
func pickLogoutTargets(opts *LogoutOptions, cfg *config.Config) ([]string, error) {
if opts.All {
names := make([]string, 0, len(cfg.Contexts))
@@ -116,16 +141,16 @@ func pickLogoutTargets(opts *LogoutOptions, cfg *config.Config) ([]string, error
}
if name == "" {
return nil, cmdutil.NewError(cmdutil.CodeInputMissingFlag,
"no current context set; pass --name <ctx> or --all")
"no current profile set; pass --name <profile> or --all")
}
if _, ok := cfg.Contexts[name]; !ok {
return nil, cmdutil.NewError(cmdutil.CodeLocalContextNotFound,
fmt.Sprintf("context %q not found in config", name))
return nil, cmdutil.NewError(cmdutil.CodeLocalProfileNotFound,
fmt.Sprintf("profile %q not found in config", name))
}
return []string{name}, nil
}
// clearContextSecrets best-effort deletes every secret slot the context
// clearContextSecrets best-effort deletes every secret slot the profile
// references. Errors are swallowed because a missing secret is a no-op
// (tested in keyring_test.go) - we don't want a stale ref to block logout.
func clearContextSecrets(store secrets.Store, c config.Context, name string) {
+11 -9
View File
@@ -10,6 +10,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/prompt"
"github.com/Tencent/WeKnora/cli/internal/secrets"
)
@@ -20,8 +21,9 @@ import (
func newLogoutFactory(t *testing.T, cfg *config.Config, store secrets.Store) *cmdutil.Factory {
t.Helper()
return &cmdutil.Factory{
Config: func() (*config.Config, error) { return cfg, nil },
Secrets: func() (secrets.Store, error) { return store, nil },
Config: func() (*config.Config, error) { return cfg, nil },
Secrets: func() (secrets.Store, error) { return store, nil },
Prompter: func() prompt.Prompter { return &prompt.AgentPrompter{} },
}
}
@@ -45,7 +47,7 @@ func TestLogout_CurrentContext(t *testing.T) {
"staging": {Host: "https://staging", APIKeyRef: store.Ref("staging", "api_key")},
},
}
require.NoError(t, runLogout(&LogoutOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, newLogoutFactory(t, cfg, store)))
require.NoError(t, runLogout(&LogoutOptions{Yes: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, newLogoutFactory(t, cfg, store)))
assert.Empty(t, cfg.CurrentContext, "current_context should clear when removed")
assert.NotContains(t, cfg.Contexts, "prod")
@@ -73,7 +75,7 @@ func TestLogout_NamedContext(t *testing.T) {
"staging": {Host: "https://staging", APIKeyRef: store.Ref("staging", "api_key")},
},
}
require.NoError(t, runLogout(&LogoutOptions{Name: "staging"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, newLogoutFactory(t, cfg, store)))
require.NoError(t, runLogout(&LogoutOptions{Name: "staging", Yes: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, newLogoutFactory(t, cfg, store)))
assert.Equal(t, "prod", cfg.CurrentContext, "current_context untouched when removing other")
assert.NotContains(t, cfg.Contexts, "staging")
@@ -91,7 +93,7 @@ func TestLogout_All(t *testing.T) {
"staging": {Host: "https://staging"},
},
}
require.NoError(t, runLogout(&LogoutOptions{All: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, newLogoutFactory(t, cfg, store)))
require.NoError(t, runLogout(&LogoutOptions{All: true, Yes: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, newLogoutFactory(t, cfg, store)))
assert.Empty(t, cfg.Contexts)
assert.Empty(t, cfg.CurrentContext)
@@ -101,7 +103,7 @@ func TestLogout_NoContexts(t *testing.T) {
isolateConfig(t)
_, _ = iostreams.SetForTest(t)
cfg := &config.Config{}
err := runLogout(&LogoutOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, newLogoutFactory(t, cfg, secrets.NewMemStore()))
err := runLogout(&LogoutOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, newLogoutFactory(t, cfg, secrets.NewMemStore()))
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
@@ -115,11 +117,11 @@ func TestLogout_UnknownName(t *testing.T) {
CurrentContext: "prod",
Contexts: map[string]config.Context{"prod": {Host: "https://prod"}},
}
err := runLogout(&LogoutOptions{Name: "ghost"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, newLogoutFactory(t, cfg, secrets.NewMemStore()))
err := runLogout(&LogoutOptions{Name: "ghost"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, newLogoutFactory(t, cfg, secrets.NewMemStore()))
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
assert.Equal(t, cmdutil.CodeLocalContextNotFound, typed.Code)
assert.Equal(t, cmdutil.CodeLocalProfileNotFound, typed.Code)
}
func TestLogout_NoCurrentNoFlag(t *testing.T) {
@@ -128,7 +130,7 @@ func TestLogout_NoCurrentNoFlag(t *testing.T) {
cfg := &config.Config{
Contexts: map[string]config.Context{"prod": {Host: "https://prod"}},
}
err := runLogout(&LogoutOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, newLogoutFactory(t, cfg, secrets.NewMemStore()))
err := runLogout(&LogoutOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, newLogoutFactory(t, cfg, secrets.NewMemStore()))
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
+16 -16
View File
@@ -12,26 +12,26 @@ import (
)
type RefreshOptions struct {
Name string // --name: target context (defaults to current)
Name string // --name: target profile (defaults to current)
}
// authRefreshFields enumerates the fields surfaced for `--format json` discovery
// on `auth refresh`. Token values are intentionally omitted - see refreshResult.
var authRefreshFields = []string{"context"}
var authRefreshFields = []string{"profile"}
// 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"`
Profile string `json:"profile"`
}
// 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.
//
// API-key contexts are rejected - they have no refresh semantic;
// API-key profiles are rejected - they have no refresh semantic;
// rotate the key via the server UI instead.
func NewCmdRefresh(f *cmdutil.Factory) *cobra.Command {
opts := &RefreshOptions{}
@@ -42,10 +42,10 @@ func NewCmdRefresh(f *cmdutil.Factory) *cobra.Command {
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
API-key profiles 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`,
Example: ` weknora auth refresh # refresh the current profile
weknora auth refresh --name staging # refresh a specific profile`,
Args: cobra.NoArgs,
RunE: func(c *cobra.Command, _ []string) error {
fopts, err := cmdutil.CheckFormatFlag(c)
@@ -56,7 +56,7 @@ refresh semantic. Rotate the key in the server UI instead.`,
return runRefresh(c.Context(), opts, fopts, f, defaultRefresher)
},
}
cmd.Flags().StringVar(&opts.Name, "name", "", "Context to refresh (defaults to the current context)")
cmd.Flags().StringVar(&opts.Name, "name", "", "Profile to refresh (defaults to the current profile)")
cmdutil.AddFormatFlag(cmd, authRefreshFields...)
return cmd
}
@@ -79,25 +79,25 @@ func runRefresh(ctx context.Context, opts *RefreshOptions, fopts *cmdutil.Format
}
if name == "" {
return cmdutil.NewError(cmdutil.CodeAuthUnauthenticated,
"no current context configured; run `weknora auth login` to set one up")
"no current profile 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))
return cmdutil.NewError(cmdutil.CodeLocalProfileNotFound,
fmt.Sprintf("profile not found: %s", name))
}
if c.Host == "" {
return cmdutil.NewError(cmdutil.CodeLocalConfigCorrupt,
fmt.Sprintf("context %q has no host", name))
fmt.Sprintf("profile %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`"
hint := "api-key profiles 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),
Message: fmt.Sprintf("profile %q has no refresh token", name),
Hint: hint,
}
}
@@ -111,8 +111,8 @@ func runRefresh(ctx context.Context, opts *RefreshOptions, fopts *cmdutil.Format
}
if fopts.WantsJSON() {
return fopts.Emit(iostreams.IO.Out, refreshResult{Context: name})
return fopts.Emit(iostreams.IO.Out, refreshResult{Profile: name}, nil)
}
fmt.Fprintf(iostreams.IO.Out, "✓ Refreshed access token for context %s\n", name)
fmt.Fprintf(iostreams.IO.Out, "✓ Refreshed access token for profile %s\n", name)
return nil
}
+14 -8
View File
@@ -2,6 +2,7 @@ package auth
import (
"context"
"encoding/json"
"errors"
"strings"
"testing"
@@ -71,7 +72,7 @@ func TestRefresh_Happy(t *testing.T) {
AccessToken: "new-access",
RefreshToken: "new-refresh",
}}
require.NoError(t, runRefresh(context.Background(), &RefreshOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, stubSvc(svc)))
require.NoError(t, runRefresh(context.Background(), &RefreshOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, f, stubSvc(svc)))
assert.Equal(t, "old-refresh", svc.gotTok, "must pass stored refresh token to SDK")
gotAccess, _ := store.Get("prod", "access")
@@ -96,7 +97,7 @@ func TestRefresh_NamedContext(t *testing.T) {
svc := &fakeRefreshService{resp: &sdk.RefreshTokenResponse{
Success: true, AccessToken: "new-stg-access", RefreshToken: "new-stg-refresh",
}}
require.NoError(t, runRefresh(context.Background(), &RefreshOptions{Name: "staging"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, stubSvc(svc)))
require.NoError(t, runRefresh(context.Background(), &RefreshOptions{Name: "staging"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, f, stubSvc(svc)))
assert.Equal(t, "stg-refresh", svc.gotTok, "--name=staging must refresh the staging context, not current")
// current is untouched
@@ -108,7 +109,7 @@ func TestRefresh_NamedContext(t *testing.T) {
func TestRefresh_NoCurrentContext(t *testing.T) {
iostreams.SetForTest(t)
f := newRefreshFactory(t, &config.Config{}, secrets.NewMemStore())
err := runRefresh(context.Background(), &RefreshOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, stubSvc(&fakeRefreshService{}))
err := runRefresh(context.Background(), &RefreshOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, f, stubSvc(&fakeRefreshService{}))
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
@@ -124,7 +125,7 @@ func TestRefresh_APIKeyContext(t *testing.T) {
Contexts: map[string]config.Context{"ci": {Host: "https://kb", APIKeyRef: "mem://ci/api_key"}},
}
f := newRefreshFactory(t, cfg, store)
err := runRefresh(context.Background(), &RefreshOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, stubSvc(&fakeRefreshService{}))
err := runRefresh(context.Background(), &RefreshOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, f, stubSvc(&fakeRefreshService{}))
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
@@ -142,7 +143,7 @@ func TestRefresh_NoRefreshTokenStored(t *testing.T) {
}
// MemStore is empty - RefreshRef points to a slot that doesn't exist.
f := newRefreshFactory(t, cfg, secrets.NewMemStore())
err := runRefresh(context.Background(), &RefreshOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, stubSvc(&fakeRefreshService{}))
err := runRefresh(context.Background(), &RefreshOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, f, stubSvc(&fakeRefreshService{}))
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
@@ -160,7 +161,7 @@ func TestRefresh_ServerRefused(t *testing.T) {
}
f := newRefreshFactory(t, cfg, store)
svc := &fakeRefreshService{resp: &sdk.RefreshTokenResponse{Success: false, Message: "refresh token expired"}}
err := runRefresh(context.Background(), &RefreshOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, stubSvc(svc))
err := runRefresh(context.Background(), &RefreshOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, f, stubSvc(svc))
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
@@ -183,7 +184,7 @@ func TestRefresh_TransportError(t *testing.T) {
}
f := newRefreshFactory(t, cfg, store)
svc := &fakeRefreshService{err: errors.New("connection reset")}
err := runRefresh(context.Background(), &RefreshOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, stubSvc(svc))
err := runRefresh(context.Background(), &RefreshOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, f, stubSvc(svc))
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
@@ -212,5 +213,10 @@ func TestRefresh_JSONOutput(t *testing.T) {
assert.NotContains(t, body, "\"r\"", "output must not leak the new refresh token")
// must mention the context name so agents can confirm what was refreshed
assert.True(t, strings.Contains(body, "prod"), "output should reference the refreshed context")
assert.NotContains(t, body, `"ok":`)
// v0.7 envelope: ok:true is expected
var env struct {
OK bool `json:"ok"`
}
require.NoError(t, json.Unmarshal([]byte(body), &env))
assert.True(t, env.OK, "envelope.ok must be true")
}
+8 -8
View File
@@ -14,7 +14,7 @@ import (
// authStatusFields enumerates the fields surfaced for `--format json` discovery
// on `auth status`. Single-resource shape: filter applies to data itself.
var authStatusFields = []string{
"context", "user_id", "username", "email", "is_active",
"profile", "user_id", "username", "email", "is_active",
"can_access_all_tenants", "tenant_id", "tenant_name",
}
@@ -28,7 +28,7 @@ type StatusService interface {
// can_access_all_tenants (cross-tenant admin) and is_active (disabled
// account) without a second round-trip.
type statusResult struct {
Context string `json:"context"`
Profile string `json:"profile"`
UserID string `json:"user_id,omitempty"`
Username string `json:"username,omitempty"`
Email string `json:"email,omitempty"`
@@ -42,13 +42,13 @@ type statusResult struct {
func NewCmdStatus(f *cmdutil.Factory) *cobra.Command {
cmd := &cobra.Command{
Use: "status",
Short: "Show the active context, principal, and token state",
Short: "Show the active profile, principal, and token state",
Long: `Live-check the active credential by calling /auth/me. Reports the user
and tenant the server resolves the credential to.
Exits with auth.unauthenticated when the token is invalid or missing - run
` + "`weknora auth login`" + ` (or ` + "`auth refresh`" + ` for JWT contexts) to recover.
For JWT contexts the SDK transparently refreshes on 401, so this command
` + "`weknora auth login`" + ` (or ` + "`auth refresh`" + ` for JWT profiles) to recover.
For JWT profiles the SDK transparently refreshes on 401, so this command
usually only surfaces a hard auth failure.`,
Args: cobra.NoArgs,
RunE: func(c *cobra.Command, args []string) error {
@@ -85,7 +85,7 @@ func runStatus(ctx context.Context, fopts *cmdutil.FormatOptions, f *cmdutil.Fac
}
if fopts.WantsJSON() {
result := statusResult{Context: cfg.CurrentContext}
result := statusResult{Profile: cfg.CurrentContext}
if user != nil {
result.UserID = user.ID
result.Username = user.Username
@@ -97,14 +97,14 @@ func runStatus(ctx context.Context, fopts *cmdutil.FormatOptions, f *cmdutil.Fac
if tenant != nil {
result.TenantName = tenant.Name
}
return fopts.Emit(iostreams.IO.Out, result)
return fopts.Emit(iostreams.IO.Out, result, nil)
}
host := ""
if c, ok := cfg.Contexts[cfg.CurrentContext]; ok {
host = c.Host
}
fmt.Fprintf(iostreams.IO.Out, "context: %s\n", cfg.CurrentContext)
fmt.Fprintf(iostreams.IO.Out, "profile: %s\n", cfg.CurrentContext)
fmt.Fprintf(iostreams.IO.Out, "host: %s\n", host)
if user != nil {
fmt.Fprintf(iostreams.IO.Out, "user: %s (%s)\n", user.Email, user.ID)
+13 -8
View File
@@ -2,8 +2,8 @@ package auth
import (
"context"
"encoding/json"
"errors"
"strings"
"testing"
"github.com/stretchr/testify/assert"
@@ -52,9 +52,9 @@ func TestRunStatus_HumanOutput(t *testing.T) {
&sdk.AuthTenant{ID: 7, Name: "Acme"},
),
}
require.NoError(t, runStatus(context.Background(), &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, svc))
require.NoError(t, runStatus(context.Background(), &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, f, svc))
got := out.String()
assert.Contains(t, got, "context: prod")
assert.Contains(t, got, "profile: prod")
assert.Contains(t, got, "host: https://kb.example.com")
assert.Contains(t, got, "alice@example.com")
assert.Contains(t, got, "Acme")
@@ -71,14 +71,19 @@ func TestRunStatus_JSONOutput(t *testing.T) {
svc := &fakeStatusService{resp: newCurrentUserResponse(&sdk.AuthUser{ID: "u1", Email: "a@b.c", TenantID: 7}, nil)}
require.NoError(t, runStatus(context.Background(), &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, f, svc))
got := out.String()
assert.True(t, strings.HasPrefix(strings.TrimSpace(got), `{"context":"prod"`), "expected bare object, got: %q", got)
assert.NotContains(t, got, `"ok":`)
var env struct {
OK bool `json:"ok"`
Data map[string]any `json:"data"`
}
require.NoError(t, json.Unmarshal([]byte(got), &env), "expected valid JSON envelope, got: %q", got)
assert.True(t, env.OK, "envelope.ok must be true")
assert.Equal(t, "prod", env.Data["profile"], "profile field should be prod")
assert.Contains(t, got, `"email":"a@b.c"`)
}
func TestRunStatus_NoSDKClient(t *testing.T) {
iostreams.SetForTest(t)
err := runStatus(context.Background(), &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, &cmdutil.Factory{}, nil)
err := runStatus(context.Background(), &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, &cmdutil.Factory{}, nil)
require.Error(t, err)
assert.True(t, cmdutil.IsAuthError(err))
}
@@ -88,7 +93,7 @@ func TestRunStatus_SDKError_Transport(t *testing.T) {
testutil.XDGTempDir(t)
require.NoError(t, config.Save(&config.Config{CurrentContext: "p", Contexts: map[string]config.Context{"p": {Host: "https://x"}}}))
f := &cmdutil.Factory{Config: func() (*config.Config, error) { return config.Load() }}
err := runStatus(context.Background(), &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, &fakeStatusService{err: assert.AnError})
err := runStatus(context.Background(), &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, f, &fakeStatusService{err: assert.AnError})
require.Error(t, err)
// Non-HTTP errors (DNS / TCP) are transport problems, not auth problems -
// classify network.error so retry logic / exit code 7 / IsTransient apply.
@@ -100,7 +105,7 @@ func TestRunStatus_SDKError_HTTP401(t *testing.T) {
testutil.XDGTempDir(t)
require.NoError(t, config.Save(&config.Config{CurrentContext: "p", Contexts: map[string]config.Context{"p": {Host: "https://x"}}}))
f := &cmdutil.Factory{Config: func() (*config.Config, error) { return config.Load() }}
err := runStatus(context.Background(), &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, &fakeStatusService{err: errors.New("HTTP error 401: invalid token")})
err := runStatus(context.Background(), &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}, f, &fakeStatusService{err: errors.New("HTTP error 401: invalid token")})
require.Error(t, err)
assert.True(t, cmdutil.IsAuthError(err))
}
+19 -19
View File
@@ -11,15 +11,15 @@ import (
// authTokenFields lists fields surfaced in `--help` as a hint for `--jq`
// projection. Single-resource shape: emits the bare token object directly.
var authTokenFields = []string{"token", "mode", "context"}
var authTokenFields = []string{"token", "mode", "profile"}
type tokenResult struct {
Token string `json:"token"`
Mode string `json:"mode"` // ModeBearer (JWT) or ModeAPIKey
Context string `json:"context"`
Profile string `json:"profile"`
}
// NewCmdToken builds `weknora auth token`. Prints the active context's
// NewCmdToken builds `weknora auth token`. Prints the active profile's
// credential to stdout for use in shell pipelines, e.g.
//
// WEKNORA_TOKEN=$(weknora auth token)
@@ -27,27 +27,27 @@ type tokenResult struct {
// curl -H "X-API-Key: $WEKNORA_TOKEN" ... # api-key mode
//
// The user is responsible for constructing the appropriate header -
// `auth list` shows which mode each context uses.
// `auth list` shows which mode each profile uses.
//
// Default output: raw token on stdout, no trailing newline (clean $(...)).
// `--format json[=fields]` emits a bare {token, mode, context} object.
// `--format json[=fields]` emits a bare {token, mode, profile} object.
func NewCmdToken(f *cmdutil.Factory) *cobra.Command {
cmd := &cobra.Command{
Use: "token",
Short: "Print the active context's credential to stdout",
Long: `Print the active context's credential to stdout, with no trailing
Short: "Print the active profile's credential to stdout",
Long: `Print the active profile's credential to stdout, with no trailing
newline, suitable for shell command substitution.
The credential is the long-lived API key (mode: api-key) or the access JWT
(mode: bearer), depending on how the context was created. Run ` + "`weknora auth list`" + `
to see which mode each context uses, and construct the matching HTTP header:
(mode: bearer), depending on how the profile was created. Run ` + "`weknora auth list`" + `
to see which mode each profile uses, and construct the matching HTTP header:
Authorization: Bearer <token> # bearer mode
X-API-Key: <token> # api-key mode
` + "`--context <name>`" + ` (global flag) selects a non-active context to read from.`,
` + "`--profile <name>`" + ` (global flag) selects a non-active profile to read from.`,
Example: ` WEKNORA_TOKEN=$(weknora auth token)
weknora auth token --context staging
weknora auth token --profile staging
weknora auth token --format json`,
Args: cobra.NoArgs,
RunE: func(c *cobra.Command, _ []string) error {
@@ -69,17 +69,17 @@ func runToken(f *cmdutil.Factory, fopts *cmdutil.FormatOptions) error {
return err
}
ctxName := cfg.CurrentContext
if f.ContextOverride != "" {
ctxName = f.ContextOverride
if f.ProfileOverride != "" {
ctxName = f.ProfileOverride
}
if ctxName == "" {
return cmdutil.NewError(cmdutil.CodeAuthUnauthenticated,
"no current context configured")
"no current profile configured")
}
ctx, ok := cfg.Contexts[ctxName]
if !ok {
return cmdutil.NewError(cmdutil.CodeLocalContextNotFound,
fmt.Sprintf("context %q not found", ctxName))
return cmdutil.NewError(cmdutil.CodeLocalProfileNotFound,
fmt.Sprintf("profile %q not found", ctxName))
}
store, err := f.Secrets()
@@ -106,16 +106,16 @@ func runToken(f *cmdutil.Factory, fopts *cmdutil.FormatOptions) error {
token, mode = v, ModeAPIKey
default:
return cmdutil.NewError(cmdutil.CodeAuthUnauthenticated,
fmt.Sprintf("context %q has no stored credential; run `weknora auth login`", ctxName))
fmt.Sprintf("profile %q has no stored credential; run `weknora auth login`", ctxName))
}
if token == "" {
return cmdutil.NewError(cmdutil.CodeAuthUnauthenticated,
fmt.Sprintf("context %q credential is empty in keyring; run `weknora auth login`", ctxName))
fmt.Sprintf("profile %q credential is empty in keyring; run `weknora auth login`", ctxName))
}
if fopts.WantsJSON() {
return fopts.Emit(iostreams.IO.Out, tokenResult{Token: token, Mode: mode, Context: ctxName})
return fopts.Emit(iostreams.IO.Out, tokenResult{Token: token, Mode: mode, Profile: ctxName}, nil)
}
// No trailing newline - clean $(weknora auth token) substitution.
+23 -18
View File
@@ -34,7 +34,7 @@ func TestAuthToken_BearerMode_PlainOutput(t *testing.T) {
_ = store.Set("prod", "access", "jwt-token-xyz")
out, _ := iostreams.SetForTest(t)
err := runToken(tokenTestFactory(t, cfg, store), &cmdutil.FormatOptions{Mode: cmdutil.FormatText})
err := runToken(tokenTestFactory(t, cfg, store), &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman})
if err != nil {
t.Fatalf("runToken: %v", err)
}
@@ -58,7 +58,7 @@ func TestAuthToken_APIKeyMode_PlainOutput(t *testing.T) {
_ = store.Set("ci", "api_key", "sk_test_apikey_42")
out, _ := iostreams.SetForTest(t)
if err := runToken(tokenTestFactory(t, cfg, store), &cmdutil.FormatOptions{Mode: cmdutil.FormatText}); err != nil {
if err := runToken(tokenTestFactory(t, cfg, store), &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}); err != nil {
t.Fatalf("runToken: %v", err)
}
if got := out.String(); got != "sk_test_apikey_42" {
@@ -80,15 +80,19 @@ func TestAuthToken_JSON(t *testing.T) {
if err := runToken(tokenTestFactory(t, cfg, store), &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}); err != nil {
t.Fatalf("runToken: %v", err)
}
var got struct {
Token string `json:"token"`
Mode string `json:"mode"`
Context string `json:"context"`
var env struct {
OK bool `json:"ok"`
Data struct {
Token string `json:"token"`
Mode string `json:"mode"`
Profile string `json:"profile"`
} `json:"data"`
}
if err := json.Unmarshal(out.Bytes(), &got); err != nil {
if err := json.Unmarshal(out.Bytes(), &env); err != nil {
t.Fatalf("parse: %v\n%s", err, out.String())
}
if got.Token != "jwt-xyz" || got.Mode != "bearer" || got.Context != "prod" {
got := env.Data
if got.Token != "jwt-xyz" || got.Mode != "bearer" || got.Profile != "prod" {
t.Errorf("payload wrong: %+v", got)
}
}
@@ -104,7 +108,8 @@ func TestAuthToken_JSON_JQProjection(t *testing.T) {
_ = store.Set("ci", "api_key", "sk_42")
out, _ := iostreams.SetForTest(t)
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON, JQ: "{token}"}
// jq projects from the envelope; .data | {token} extracts from the data object inside envelope.
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON, JQ: ".data | {token}"}
if err := runToken(tokenTestFactory(t, cfg, store), fopts); err != nil {
t.Fatalf("runToken: %v", err)
}
@@ -124,7 +129,7 @@ func TestAuthToken_NoCurrentContext(t *testing.T) {
cfg := &config.Config{}
store := secrets.NewMemStore()
iostreams.SetForTest(t)
err := runToken(tokenTestFactory(t, cfg, store), &cmdutil.FormatOptions{Mode: cmdutil.FormatText})
err := runToken(tokenTestFactory(t, cfg, store), &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman})
if err == nil {
t.Fatal("expected error, got nil")
}
@@ -133,7 +138,7 @@ func TestAuthToken_NoCurrentContext(t *testing.T) {
}
}
func TestAuthToken_ContextOverride(t *testing.T) {
func TestAuthToken_ProfileOverride(t *testing.T) {
cfg := &config.Config{
CurrentContext: "prod",
Contexts: map[string]config.Context{
@@ -146,10 +151,10 @@ func TestAuthToken_ContextOverride(t *testing.T) {
_ = store.Set("staging", "api_key", "staging-key")
f := tokenTestFactory(t, cfg, store)
f.ContextOverride = "staging"
f.ProfileOverride = "staging"
out, _ := iostreams.SetForTest(t)
if err := runToken(f, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}); err != nil {
if err := runToken(f, &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}); err != nil {
t.Fatalf("runToken: %v", err)
}
if got := out.String(); got != "staging-key" {
@@ -167,7 +172,7 @@ func TestAuthToken_NoStoredCredential(t *testing.T) {
store := secrets.NewMemStore()
// no Set - keyring is empty
iostreams.SetForTest(t)
err := runToken(tokenTestFactory(t, cfg, store), &cmdutil.FormatOptions{Mode: cmdutil.FormatText})
err := runToken(tokenTestFactory(t, cfg, store), &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman})
if err == nil {
t.Fatal("expected auth.unauthenticated, got nil")
}
@@ -185,7 +190,7 @@ func TestAuthToken_ContextWithNoCredentialRefs(t *testing.T) {
}
store := secrets.NewMemStore()
iostreams.SetForTest(t)
err := runToken(tokenTestFactory(t, cfg, store), &cmdutil.FormatOptions{Mode: cmdutil.FormatText})
err := runToken(tokenTestFactory(t, cfg, store), &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman})
if err == nil {
t.Fatal("expected auth.unauthenticated, got nil")
}
@@ -229,7 +234,7 @@ func makeAPIKeyCfg() (*config.Config, *secrets.MemStore) {
func TestAuthToken_NonTTY_NoStderrHint(t *testing.T) {
cfg, store := makeBearerCfg()
out, errBuf := iostreams.SetForTest(t)
if err := runToken(tokenTestFactory(t, cfg, store), &cmdutil.FormatOptions{Mode: cmdutil.FormatText}); err != nil {
if err := runToken(tokenTestFactory(t, cfg, store), &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}); err != nil {
t.Fatalf("runToken: %v", err)
}
if out.String() != "jwt-xyz" {
@@ -243,7 +248,7 @@ func TestAuthToken_NonTTY_NoStderrHint(t *testing.T) {
func TestAuthToken_TTY_BearerMode_StderrHintNoRotationNote(t *testing.T) {
cfg, store := makeBearerCfg()
out, errBuf := iostreams.SetForTestWithTTY(t)
if err := runToken(tokenTestFactory(t, cfg, store), &cmdutil.FormatOptions{Mode: cmdutil.FormatText}); err != nil {
if err := runToken(tokenTestFactory(t, cfg, store), &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}); err != nil {
t.Fatalf("runToken: %v", err)
}
if out.String() != "jwt-xyz" {
@@ -260,7 +265,7 @@ func TestAuthToken_TTY_BearerMode_StderrHintNoRotationNote(t *testing.T) {
func TestAuthToken_TTY_APIKeyMode_IncludesRotationNote(t *testing.T) {
cfg, store := makeAPIKeyCfg()
out, errBuf := iostreams.SetForTestWithTTY(t)
if err := runToken(tokenTestFactory(t, cfg, store), &cmdutil.FormatOptions{Mode: cmdutil.FormatText}); err != nil {
if err := runToken(tokenTestFactory(t, cfg, store), &cmdutil.FormatOptions{Mode: cmdutil.FormatHuman}); err != nil {
t.Fatalf("runToken: %v", err)
}
if out.String() != "sk_42" {