feat(cli): --log-level + kb/agent status & check + cross-cutting refactor
Operability surface and the bulk of the jopts→fopts migration: * --log-level error|warn|info|debug + WEKNORA_LOG_LEVEL env, wired to the SDK via client.SetDebugLevel. Invalid --log-level returns FlagError (exit 2). * kb status <kb-id> / kb check <kb-id> verb split (1 HTTP vs 1+N for failed_count aggregation). * agent status <agent-id> / agent check <agent-id> verb split (probes kb_scope_all_reachable via 1+N HTTP). * kb create <name> positional (matches agent create). * Positional id help strings namespaced (<kb-id> / <agent-id>). * All auth / context / link / doctor / kb / agent CRUD commands migrated to the FormatOptions API. * root.go Execute(ctx) takes a context so signal-cancellation propagates via cmd.Context() into long-running commands. * Pagination termination uses len(accum) >= total (not page*pageSize) so server-capped page sizes do not truncate aggregations.
This commit is contained in:
@@ -31,7 +31,7 @@ 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", "json"} {
|
||||
for _, name := range []string{"host", "name", "with-token", "format"} {
|
||||
assert.NotNilf(t, cmd.Flags().Lookup(name), "flag %s missing", name)
|
||||
}
|
||||
// `--context` should NOT be a local flag (it's the global persistent flag).
|
||||
@@ -46,7 +46,7 @@ func TestNewCmdLogin_InvokesRunF(t *testing.T) {
|
||||
f := &cmdutil.Factory{
|
||||
Secrets: func() (secrets.Store, error) { return store, nil },
|
||||
}
|
||||
cmd := NewCmdLogin(f, func(_ context.Context, opts *LoginOptions, _ *cmdutil.JSONOptions, _ *cmdutil.Factory, _ LoginService) error {
|
||||
cmd := NewCmdLogin(f, func(_ context.Context, opts *LoginOptions, _ *cmdutil.FormatOptions, _ *cmdutil.Factory, _ LoginService) error {
|
||||
called = true
|
||||
assert.Equal(t, "https://kb.example.com", opts.Host)
|
||||
assert.True(t, opts.WithToken)
|
||||
@@ -76,7 +76,7 @@ func TestPersistAPIKey_WritesContext(t *testing.T) {
|
||||
Context: "ci",
|
||||
APIKey: "sk-zzz",
|
||||
}
|
||||
require.NoError(t, persistAPIKey(opts, &cmdutil.JSONOptions{}, f, nil))
|
||||
require.NoError(t, persistAPIKey(opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, nil))
|
||||
v, _ := store.Get("ci", "api_key")
|
||||
assert.Equal(t, "sk-zzz", v)
|
||||
cfg, _ := f.Config()
|
||||
@@ -104,7 +104,7 @@ func TestPersistJWT_StoresBothTokens(t *testing.T) {
|
||||
RefreshToken: "jwt-ref",
|
||||
User: &sdk.AuthUser{Email: "a@b.c", TenantID: 7},
|
||||
}
|
||||
require.NoError(t, persistJWT(opts, &cmdutil.JSONOptions{}, f, resp))
|
||||
require.NoError(t, persistJWT(opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, f, resp))
|
||||
a, _ := store.Get("p", "access")
|
||||
r, _ := store.Get("p", "refresh")
|
||||
assert.Equal(t, "jwt-acc", a)
|
||||
|
||||
@@ -14,7 +14,7 @@ import (
|
||||
|
||||
type ListOptions struct{}
|
||||
|
||||
// authListFields enumerates the fields surfaced for `--json` discovery on
|
||||
// authListFields enumerates the fields surfaced for `--format json` discovery on
|
||||
// `auth list`. Each entry is a per-context summary row.
|
||||
var authListFields = []string{
|
||||
"name", "host", "user", "mode", "current",
|
||||
@@ -38,18 +38,19 @@ func NewCmdList(f *cmdutil.Factory) *cobra.Command {
|
||||
Long: `Show every configured context (name, host, user, mode, current). Read-only; no network or keyring access.`,
|
||||
Args: cobra.NoArgs,
|
||||
RunE: func(c *cobra.Command, _ []string) error {
|
||||
jopts, err := cmdutil.CheckJSONFlags(c)
|
||||
fopts, err := cmdutil.CheckFormatFlag(c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return runList(jopts, f)
|
||||
fopts.ResolveDefault(iostreams.IO.IsStdoutTTY())
|
||||
return runList(fopts, f)
|
||||
},
|
||||
}
|
||||
cmdutil.AddJSONFlags(cmd, authListFields)
|
||||
cmdutil.AddFormatFlag(cmd, authListFields...)
|
||||
return cmd
|
||||
}
|
||||
|
||||
func runList(jopts *cmdutil.JSONOptions, f *cmdutil.Factory) error {
|
||||
func runList(fopts *cmdutil.FormatOptions, f *cmdutil.Factory) error {
|
||||
cfg, err := f.Config()
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -66,8 +67,8 @@ func runList(jopts *cmdutil.JSONOptions, f *cmdutil.Factory) error {
|
||||
}
|
||||
sort.Slice(entries, func(i, j int) bool { return entries[i].Name < entries[j].Name })
|
||||
|
||||
if jopts.Enabled() {
|
||||
return jopts.Emit(iostreams.IO.Out, entries)
|
||||
if fopts.WantsJSON() {
|
||||
return fopts.Emit(iostreams.IO.Out, entries)
|
||||
}
|
||||
if len(entries) == 0 {
|
||||
fmt.Fprintln(iostreams.IO.Out, "No contexts configured. Run `weknora auth login` to create one.")
|
||||
|
||||
@@ -28,7 +28,7 @@ func TestList_HumanRender(t *testing.T) {
|
||||
"staging": {Host: "https://staging", APIKeyRef: "keychain://staging/api_key"},
|
||||
},
|
||||
}
|
||||
require.NoError(t, runList(nil, newListFactory(cfg)))
|
||||
require.NoError(t, runList(&cmdutil.FormatOptions{Mode: cmdutil.FormatText}, newListFactory(cfg)))
|
||||
|
||||
got := out.String()
|
||||
// One row per context, current marked with `*`.
|
||||
@@ -44,7 +44,7 @@ func TestList_HumanRender(t *testing.T) {
|
||||
|
||||
func TestList_Empty(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
require.NoError(t, runList(nil, newListFactory(&config.Config{})))
|
||||
require.NoError(t, runList(&cmdutil.FormatOptions{Mode: cmdutil.FormatText}, newListFactory(&config.Config{})))
|
||||
assert.Contains(t, out.String(), "No contexts configured")
|
||||
}
|
||||
|
||||
@@ -57,7 +57,7 @@ func TestList_JSON_BareArray(t *testing.T) {
|
||||
"staging": {Host: "https://staging", APIKeyRef: "key"},
|
||||
},
|
||||
}
|
||||
require.NoError(t, runList(&cmdutil.JSONOptions{}, newListFactory(cfg)))
|
||||
require.NoError(t, runList(&cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, newListFactory(cfg)))
|
||||
|
||||
var got []listEntry
|
||||
require.NoError(t, json.Unmarshal(out.Bytes(), &got))
|
||||
|
||||
+17
-16
@@ -15,7 +15,7 @@ import (
|
||||
sdk "github.com/Tencent/WeKnora/client"
|
||||
)
|
||||
|
||||
// authLoginFields enumerates the fields surfaced for `--json` discovery on
|
||||
// authLoginFields enumerates the fields surfaced for `--format json` discovery on
|
||||
// `auth login`. The post-login summary has no token values - they stay in the
|
||||
// keyring; agents who need to verify the credential should re-run
|
||||
// `auth status`.
|
||||
@@ -64,7 +64,7 @@ var defaultAPIKeyValidator apiKeyValidator = func(ctx context.Context, host, api
|
||||
|
||||
// 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 {
|
||||
func NewCmdLogin(f *cmdutil.Factory, runF func(context.Context, *LoginOptions, *cmdutil.FormatOptions, *cmdutil.Factory, LoginService) error) *cobra.Command {
|
||||
opts := &LoginOptions{}
|
||||
cmd := &cobra.Command{
|
||||
Use: "login",
|
||||
@@ -76,10 +76,11 @@ Credentials are persisted to the OS keyring when available; otherwise to a
|
||||
the current_context in ~/.config/weknora/config.yaml.`,
|
||||
Args: cobra.NoArgs,
|
||||
RunE: func(c *cobra.Command, args []string) error {
|
||||
jopts, err := cmdutil.CheckJSONFlags(c)
|
||||
fopts, err := cmdutil.CheckFormatFlag(c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fopts.ResolveDefault(iostreams.IO.IsStdoutTTY())
|
||||
run := runF
|
||||
if run == nil {
|
||||
run = runLogin
|
||||
@@ -88,13 +89,13 @@ the current_context in ~/.config/weknora/config.yaml.`,
|
||||
if opts.StdinReader == nil {
|
||||
opts.StdinReader = iostreams.IO.In
|
||||
}
|
||||
return run(c.Context(), opts, jopts, f, svc)
|
||||
return run(c.Context(), opts, fopts, f, svc)
|
||||
},
|
||||
}
|
||||
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().BoolVar(&opts.WithToken, "with-token", false, "Read an API key from stdin instead of prompting for password")
|
||||
cmdutil.AddJSONFlags(cmd, authLoginFields)
|
||||
cmdutil.AddFormatFlag(cmd, authLoginFields...)
|
||||
_ = cmd.MarkFlagRequired("host")
|
||||
return cmd
|
||||
}
|
||||
@@ -108,7 +109,7 @@ func loginServiceFor(host string) LoginService {
|
||||
return sdk.NewClient(host)
|
||||
}
|
||||
|
||||
func runLogin(ctx context.Context, opts *LoginOptions, jopts *cmdutil.JSONOptions, f *cmdutil.Factory, svc LoginService) error {
|
||||
func runLogin(ctx context.Context, opts *LoginOptions, fopts *cmdutil.FormatOptions, f *cmdutil.Factory, svc LoginService) error {
|
||||
if err := validateHost(opts.Host); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -129,7 +130,7 @@ func runLogin(ctx context.Context, opts *LoginOptions, jopts *cmdutil.JSONOption
|
||||
if err != nil {
|
||||
return cmdutil.Wrapf(cmdutil.CodeAuthBadCredential, err, "validate API key")
|
||||
}
|
||||
return persistAPIKey(opts, jopts, f, user)
|
||||
return persistAPIKey(opts, fopts, f, user)
|
||||
}
|
||||
|
||||
// Interactive: prompt for email + password.
|
||||
@@ -162,14 +163,14 @@ func runLogin(ctx context.Context, opts *LoginOptions, jopts *cmdutil.JSONOption
|
||||
return cmdutil.NewError(cmdutil.CodeAuthBadCredential, fmt.Sprintf("login refused: %s", resp.Message))
|
||||
}
|
||||
|
||||
return persistJWT(opts, jopts, f, resp)
|
||||
return persistJWT(opts, fopts, f, resp)
|
||||
}
|
||||
|
||||
// persistAPIKey saves the --with-token API key and writes the context.
|
||||
// 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 {
|
||||
func persistAPIKey(opts *LoginOptions, fopts *cmdutil.FormatOptions, f *cmdutil.Factory, user *sdk.AuthUser) error {
|
||||
store, err := f.Secrets()
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -186,11 +187,11 @@ func persistAPIKey(opts *LoginOptions, jopts *cmdutil.JSONOptions, f *cmdutil.Fa
|
||||
ctx.User = user.Email
|
||||
ctx.TenantID = user.TenantID
|
||||
}
|
||||
return saveContextRef(opts, jopts, f, ctx, user)
|
||||
return saveContextRef(opts, fopts, f, ctx, user)
|
||||
}
|
||||
|
||||
// persistJWT saves access + refresh tokens and writes the context.
|
||||
func persistJWT(opts *LoginOptions, jopts *cmdutil.JSONOptions, f *cmdutil.Factory, resp *sdk.LoginResponse) error {
|
||||
func persistJWT(opts *LoginOptions, fopts *cmdutil.FormatOptions, f *cmdutil.Factory, resp *sdk.LoginResponse) error {
|
||||
store, err := f.Secrets()
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -213,10 +214,10 @@ func persistJWT(opts *LoginOptions, jopts *cmdutil.JSONOptions, f *cmdutil.Facto
|
||||
c.User = resp.User.Email
|
||||
c.TenantID = resp.User.TenantID
|
||||
}
|
||||
return saveContextRef(opts, jopts, f, c, resp.User)
|
||||
return saveContextRef(opts, fopts, f, c, resp.User)
|
||||
}
|
||||
|
||||
// loginResult is the typed payload emitted by `--json`. mode is derived from
|
||||
// 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"`
|
||||
@@ -227,7 +228,7 @@ type loginResult struct {
|
||||
}
|
||||
|
||||
// saveContextRef writes the context to config.yaml and prints success.
|
||||
func saveContextRef(opts *LoginOptions, jopts *cmdutil.JSONOptions, f *cmdutil.Factory, ctx *config.Context, user *sdk.AuthUser) error {
|
||||
func saveContextRef(opts *LoginOptions, fopts *cmdutil.FormatOptions, f *cmdutil.Factory, ctx *config.Context, user *sdk.AuthUser) error {
|
||||
cfg, err := f.Config()
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -240,14 +241,14 @@ func saveContextRef(opts *LoginOptions, jopts *cmdutil.JSONOptions, f *cmdutil.F
|
||||
if err := config.Save(cfg); err != nil {
|
||||
return cmdutil.Wrapf(cmdutil.CodeLocalFileIO, err, "save config")
|
||||
}
|
||||
if jopts.Enabled() {
|
||||
if fopts.WantsJSON() {
|
||||
result := loginResult{Context: opts.Context, Host: opts.Host, Mode: ModeAPIKey}
|
||||
if user != nil {
|
||||
result.Mode = ModeBearer
|
||||
result.User = user.Email
|
||||
result.TenantID = user.TenantID
|
||||
}
|
||||
return jopts.Emit(iostreams.IO.Out, result)
|
||||
return fopts.Emit(iostreams.IO.Out, result)
|
||||
}
|
||||
who := opts.Context
|
||||
if user != nil {
|
||||
|
||||
@@ -62,7 +62,7 @@ func TestRunLogin_PasswordMode(t *testing.T) {
|
||||
Host: "https://kb.example.com",
|
||||
Context: "prod",
|
||||
}
|
||||
require.NoError(t, runLogin(context.Background(), opts, nil, f, svc))
|
||||
require.NoError(t, runLogin(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, 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, nil, f, nil))
|
||||
require.NoError(t, runLogin(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, nil))
|
||||
got, _ := store.Get("ci", "api_key")
|
||||
assert.Equal(t, "sk-1234", got)
|
||||
cfg, _ := f.Config()
|
||||
@@ -105,7 +105,7 @@ func TestRunLogin_WithToken_ServerRejects(t *testing.T) {
|
||||
WithToken: true,
|
||||
StdinReader: strings.NewReader("sk-bad"),
|
||||
}
|
||||
err := runLogin(context.Background(), opts, nil, f, nil)
|
||||
err := runLogin(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, nil)
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
@@ -137,7 +137,7 @@ func TestRunLogin_WithToken_Empty(t *testing.T) {
|
||||
WithToken: true,
|
||||
StdinReader: strings.NewReader(""),
|
||||
}
|
||||
err := runLogin(context.Background(), opts, nil, f, nil)
|
||||
err := runLogin(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, nil)
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "input.missing_flag")
|
||||
}
|
||||
@@ -145,7 +145,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"}, nil, f, nil)
|
||||
err := runLogin(context.Background(), &LoginOptions{Host: "ftp://nope"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, nil)
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "input.invalid_argument")
|
||||
}
|
||||
@@ -154,7 +154,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"}, nil, f, svc)
|
||||
err := runLogin(context.Background(), &LoginOptions{Host: "https://x", Context: "p"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, svc)
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "auth.bad_credential")
|
||||
}
|
||||
|
||||
@@ -17,7 +17,7 @@ type LogoutOptions struct {
|
||||
All bool // --all: clear every context
|
||||
}
|
||||
|
||||
// authLogoutFields enumerates the fields surfaced for `--json` discovery
|
||||
// authLogoutFields enumerates the fields surfaced for `--format json` discovery
|
||||
// on `auth logout`. The result is the list of context names that were
|
||||
// logged out.
|
||||
var authLogoutFields = []string{"removed"}
|
||||
@@ -46,21 +46,22 @@ accepted until it expires.`,
|
||||
weknora auth logout --all`,
|
||||
Args: cobra.NoArgs,
|
||||
RunE: func(c *cobra.Command, _ []string) error {
|
||||
jopts, err := cmdutil.CheckJSONFlags(c)
|
||||
fopts, err := cmdutil.CheckFormatFlag(c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return runLogout(opts, jopts, f)
|
||||
fopts.ResolveDefault(iostreams.IO.IsStdoutTTY())
|
||||
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")
|
||||
cmdutil.AddJSONFlags(cmd, authLogoutFields)
|
||||
cmdutil.AddFormatFlag(cmd, authLogoutFields...)
|
||||
cmd.MarkFlagsMutuallyExclusive("name", "all")
|
||||
return cmd
|
||||
}
|
||||
|
||||
func runLogout(opts *LogoutOptions, jopts *cmdutil.JSONOptions, f *cmdutil.Factory) error {
|
||||
func runLogout(opts *LogoutOptions, fopts *cmdutil.FormatOptions, f *cmdutil.Factory) error {
|
||||
cfg, err := f.Config()
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -93,8 +94,8 @@ func runLogout(opts *LogoutOptions, jopts *cmdutil.JSONOptions, f *cmdutil.Facto
|
||||
return cmdutil.Wrapf(cmdutil.CodeLocalFileIO, err, "save config")
|
||||
}
|
||||
|
||||
if jopts.Enabled() {
|
||||
return jopts.Emit(iostreams.IO.Out, logoutResult{Removed: targets})
|
||||
if fopts.WantsJSON() {
|
||||
return fopts.Emit(iostreams.IO.Out, logoutResult{Removed: targets})
|
||||
}
|
||||
fmt.Fprintf(iostreams.IO.Out, "✓ Logged out of %d context(s): %s\n", len(targets), strings.Join(targets, ", "))
|
||||
return nil
|
||||
|
||||
@@ -45,7 +45,7 @@ func TestLogout_CurrentContext(t *testing.T) {
|
||||
"staging": {Host: "https://staging", APIKeyRef: store.Ref("staging", "api_key")},
|
||||
},
|
||||
}
|
||||
require.NoError(t, runLogout(&LogoutOptions{}, nil, newLogoutFactory(t, cfg, store)))
|
||||
require.NoError(t, runLogout(&LogoutOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, newLogoutFactory(t, cfg, store)))
|
||||
|
||||
assert.Empty(t, cfg.CurrentContext, "current_context should clear when removed")
|
||||
assert.NotContains(t, cfg.Contexts, "prod")
|
||||
@@ -73,7 +73,7 @@ func TestLogout_NamedContext(t *testing.T) {
|
||||
"staging": {Host: "https://staging", APIKeyRef: store.Ref("staging", "api_key")},
|
||||
},
|
||||
}
|
||||
require.NoError(t, runLogout(&LogoutOptions{Name: "staging"}, nil, newLogoutFactory(t, cfg, store)))
|
||||
require.NoError(t, runLogout(&LogoutOptions{Name: "staging"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, newLogoutFactory(t, cfg, store)))
|
||||
|
||||
assert.Equal(t, "prod", cfg.CurrentContext, "current_context untouched when removing other")
|
||||
assert.NotContains(t, cfg.Contexts, "staging")
|
||||
@@ -91,7 +91,7 @@ func TestLogout_All(t *testing.T) {
|
||||
"staging": {Host: "https://staging"},
|
||||
},
|
||||
}
|
||||
require.NoError(t, runLogout(&LogoutOptions{All: true}, nil, newLogoutFactory(t, cfg, store)))
|
||||
require.NoError(t, runLogout(&LogoutOptions{All: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, newLogoutFactory(t, cfg, store)))
|
||||
|
||||
assert.Empty(t, cfg.Contexts)
|
||||
assert.Empty(t, cfg.CurrentContext)
|
||||
@@ -101,7 +101,7 @@ func TestLogout_NoContexts(t *testing.T) {
|
||||
isolateConfig(t)
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
cfg := &config.Config{}
|
||||
err := runLogout(&LogoutOptions{}, nil, newLogoutFactory(t, cfg, secrets.NewMemStore()))
|
||||
err := runLogout(&LogoutOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, newLogoutFactory(t, cfg, secrets.NewMemStore()))
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
@@ -115,7 +115,7 @@ func TestLogout_UnknownName(t *testing.T) {
|
||||
CurrentContext: "prod",
|
||||
Contexts: map[string]config.Context{"prod": {Host: "https://prod"}},
|
||||
}
|
||||
err := runLogout(&LogoutOptions{Name: "ghost"}, nil, newLogoutFactory(t, cfg, secrets.NewMemStore()))
|
||||
err := runLogout(&LogoutOptions{Name: "ghost"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, newLogoutFactory(t, cfg, secrets.NewMemStore()))
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
@@ -128,7 +128,7 @@ func TestLogout_NoCurrentNoFlag(t *testing.T) {
|
||||
cfg := &config.Config{
|
||||
Contexts: map[string]config.Context{"prod": {Host: "https://prod"}},
|
||||
}
|
||||
err := runLogout(&LogoutOptions{}, nil, newLogoutFactory(t, cfg, secrets.NewMemStore()))
|
||||
err := runLogout(&LogoutOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, newLogoutFactory(t, cfg, secrets.NewMemStore()))
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
|
||||
@@ -15,7 +15,7 @@ type RefreshOptions struct {
|
||||
Name string // --name: target context (defaults to current)
|
||||
}
|
||||
|
||||
// authRefreshFields enumerates the fields surfaced for `--json` discovery
|
||||
// authRefreshFields enumerates the fields surfaced for `--format json` discovery
|
||||
// on `auth refresh`. Token values are intentionally omitted - see refreshResult.
|
||||
var authRefreshFields = []string{"context"}
|
||||
|
||||
@@ -48,15 +48,16 @@ refresh semantic. Rotate the key in the server UI instead.`,
|
||||
weknora auth refresh --name staging # refresh a specific context`,
|
||||
Args: cobra.NoArgs,
|
||||
RunE: func(c *cobra.Command, _ []string) error {
|
||||
jopts, err := cmdutil.CheckJSONFlags(c)
|
||||
fopts, err := cmdutil.CheckFormatFlag(c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return runRefresh(c.Context(), opts, jopts, f, defaultRefresher)
|
||||
fopts.ResolveDefault(iostreams.IO.IsStdoutTTY())
|
||||
return runRefresh(c.Context(), opts, fopts, f, defaultRefresher)
|
||||
},
|
||||
}
|
||||
cmd.Flags().StringVar(&opts.Name, "name", "", "Context to refresh (defaults to the current context)")
|
||||
cmdutil.AddJSONFlags(cmd, authRefreshFields)
|
||||
cmdutil.AddFormatFlag(cmd, authRefreshFields...)
|
||||
return cmd
|
||||
}
|
||||
|
||||
@@ -67,7 +68,7 @@ func defaultRefresher(host string) cmdutil.Refresher {
|
||||
return sdk.NewClient(host)
|
||||
}
|
||||
|
||||
func runRefresh(ctx context.Context, opts *RefreshOptions, jopts *cmdutil.JSONOptions, f *cmdutil.Factory, refresherFor func(host string) cmdutil.Refresher) error {
|
||||
func runRefresh(ctx context.Context, opts *RefreshOptions, fopts *cmdutil.FormatOptions, f *cmdutil.Factory, refresherFor func(host string) cmdutil.Refresher) error {
|
||||
cfg, err := f.Config()
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -109,8 +110,8 @@ func runRefresh(ctx context.Context, opts *RefreshOptions, jopts *cmdutil.JSONOp
|
||||
return err
|
||||
}
|
||||
|
||||
if jopts.Enabled() {
|
||||
return jopts.Emit(iostreams.IO.Out, refreshResult{Context: name})
|
||||
if fopts.WantsJSON() {
|
||||
return fopts.Emit(iostreams.IO.Out, refreshResult{Context: name})
|
||||
}
|
||||
fmt.Fprintf(iostreams.IO.Out, "✓ Refreshed access token for context %s\n", name)
|
||||
return nil
|
||||
|
||||
@@ -71,7 +71,7 @@ func TestRefresh_Happy(t *testing.T) {
|
||||
AccessToken: "new-access",
|
||||
RefreshToken: "new-refresh",
|
||||
}}
|
||||
require.NoError(t, runRefresh(context.Background(), &RefreshOptions{}, nil, f, stubSvc(svc)))
|
||||
require.NoError(t, runRefresh(context.Background(), &RefreshOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, stubSvc(svc)))
|
||||
|
||||
assert.Equal(t, "old-refresh", svc.gotTok, "must pass stored refresh token to SDK")
|
||||
gotAccess, _ := store.Get("prod", "access")
|
||||
@@ -96,7 +96,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"}, nil, f, stubSvc(svc)))
|
||||
require.NoError(t, runRefresh(context.Background(), &RefreshOptions{Name: "staging"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, stubSvc(svc)))
|
||||
|
||||
assert.Equal(t, "stg-refresh", svc.gotTok, "--name=staging must refresh the staging context, not current")
|
||||
// current is untouched
|
||||
@@ -108,7 +108,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{}, nil, f, stubSvc(&fakeRefreshService{}))
|
||||
err := runRefresh(context.Background(), &RefreshOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, stubSvc(&fakeRefreshService{}))
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
@@ -124,7 +124,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{}, nil, f, stubSvc(&fakeRefreshService{}))
|
||||
err := runRefresh(context.Background(), &RefreshOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, stubSvc(&fakeRefreshService{}))
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
@@ -142,7 +142,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{}, nil, f, stubSvc(&fakeRefreshService{}))
|
||||
err := runRefresh(context.Background(), &RefreshOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, stubSvc(&fakeRefreshService{}))
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
@@ -160,7 +160,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{}, nil, f, stubSvc(svc))
|
||||
err := runRefresh(context.Background(), &RefreshOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, stubSvc(svc))
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
@@ -183,7 +183,7 @@ func TestRefresh_TransportError(t *testing.T) {
|
||||
}
|
||||
f := newRefreshFactory(t, cfg, store)
|
||||
svc := &fakeRefreshService{err: errors.New("connection reset")}
|
||||
err := runRefresh(context.Background(), &RefreshOptions{}, nil, f, stubSvc(svc))
|
||||
err := runRefresh(context.Background(), &RefreshOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, stubSvc(svc))
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
@@ -203,7 +203,7 @@ func TestRefresh_JSONOutput(t *testing.T) {
|
||||
}
|
||||
f := newRefreshFactory(t, cfg, store)
|
||||
svc := &fakeRefreshService{resp: &sdk.RefreshTokenResponse{Success: true, AccessToken: "a", RefreshToken: "r"}}
|
||||
require.NoError(t, runRefresh(context.Background(), &RefreshOptions{}, &cmdutil.JSONOptions{}, f, stubSvc(svc)))
|
||||
require.NoError(t, runRefresh(context.Background(), &RefreshOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, f, stubSvc(svc)))
|
||||
|
||||
body := out.String()
|
||||
// payload must not leak the actual token values.
|
||||
|
||||
@@ -11,7 +11,7 @@ import (
|
||||
sdk "github.com/Tencent/WeKnora/client"
|
||||
)
|
||||
|
||||
// authStatusFields enumerates the fields surfaced for `--json` discovery
|
||||
// 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",
|
||||
@@ -23,7 +23,7 @@ type StatusService interface {
|
||||
GetCurrentUser(ctx context.Context) (*sdk.CurrentUserResponse, error)
|
||||
}
|
||||
|
||||
// statusResult is the typed payload emitted by `--json`. Mirrors the
|
||||
// statusResult is the typed payload emitted by `--format json`. Mirrors the
|
||||
// SDK AuthUser + AuthTenant projection so agents can branch on
|
||||
// can_access_all_tenants (cross-tenant admin) and is_active (disabled
|
||||
// account) without a second round-trip.
|
||||
@@ -52,22 +52,23 @@ For JWT contexts 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 {
|
||||
jopts, err := cmdutil.CheckJSONFlags(c)
|
||||
fopts, err := cmdutil.CheckFormatFlag(c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fopts.ResolveDefault(iostreams.IO.IsStdoutTTY())
|
||||
cli, err := f.Client()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return runStatus(c.Context(), jopts, f, cli)
|
||||
return runStatus(c.Context(), fopts, f, cli)
|
||||
},
|
||||
}
|
||||
cmdutil.AddJSONFlags(cmd, authStatusFields)
|
||||
cmdutil.AddFormatFlag(cmd, authStatusFields...)
|
||||
return cmd
|
||||
}
|
||||
|
||||
func runStatus(ctx context.Context, jopts *cmdutil.JSONOptions, f *cmdutil.Factory, svc StatusService) error {
|
||||
func runStatus(ctx context.Context, fopts *cmdutil.FormatOptions, f *cmdutil.Factory, svc StatusService) error {
|
||||
if svc == nil {
|
||||
return cmdutil.NewError(cmdutil.CodeAuthUnauthenticated, "no SDK client available; run `weknora auth login`")
|
||||
}
|
||||
@@ -83,7 +84,7 @@ func runStatus(ctx context.Context, jopts *cmdutil.JSONOptions, f *cmdutil.Facto
|
||||
return err
|
||||
}
|
||||
|
||||
if jopts.Enabled() {
|
||||
if fopts.WantsJSON() {
|
||||
result := statusResult{Context: cfg.CurrentContext}
|
||||
if user != nil {
|
||||
result.UserID = user.ID
|
||||
@@ -96,7 +97,7 @@ func runStatus(ctx context.Context, jopts *cmdutil.JSONOptions, f *cmdutil.Facto
|
||||
if tenant != nil {
|
||||
result.TenantName = tenant.Name
|
||||
}
|
||||
return jopts.Emit(iostreams.IO.Out, result)
|
||||
return fopts.Emit(iostreams.IO.Out, result)
|
||||
}
|
||||
|
||||
host := ""
|
||||
|
||||
@@ -52,7 +52,7 @@ func TestRunStatus_HumanOutput(t *testing.T) {
|
||||
&sdk.AuthTenant{ID: 7, Name: "Acme"},
|
||||
),
|
||||
}
|
||||
require.NoError(t, runStatus(context.Background(), nil, f, svc))
|
||||
require.NoError(t, runStatus(context.Background(), &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, svc))
|
||||
got := out.String()
|
||||
assert.Contains(t, got, "context: prod")
|
||||
assert.Contains(t, got, "host: https://kb.example.com")
|
||||
@@ -69,7 +69,7 @@ func TestRunStatus_JSONOutput(t *testing.T) {
|
||||
}))
|
||||
f := &cmdutil.Factory{Config: func() (*config.Config, error) { return config.Load() }}
|
||||
svc := &fakeStatusService{resp: newCurrentUserResponse(&sdk.AuthUser{ID: "u1", Email: "a@b.c", TenantID: 7}, nil)}
|
||||
require.NoError(t, runStatus(context.Background(), &cmdutil.JSONOptions{}, f, svc))
|
||||
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":`)
|
||||
@@ -78,7 +78,7 @@ func TestRunStatus_JSONOutput(t *testing.T) {
|
||||
|
||||
func TestRunStatus_NoSDKClient(t *testing.T) {
|
||||
iostreams.SetForTest(t)
|
||||
err := runStatus(context.Background(), nil, &cmdutil.Factory{}, nil)
|
||||
err := runStatus(context.Background(), &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, &cmdutil.Factory{}, nil)
|
||||
require.Error(t, err)
|
||||
assert.True(t, cmdutil.IsAuthError(err))
|
||||
}
|
||||
@@ -88,7 +88,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(), nil, f, &fakeStatusService{err: assert.AnError})
|
||||
err := runStatus(context.Background(), &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, 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 +100,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(), nil, f, &fakeStatusService{err: errors.New("HTTP error 401: invalid token")})
|
||||
err := runStatus(context.Background(), &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, &fakeStatusService{err: errors.New("HTTP error 401: invalid token")})
|
||||
require.Error(t, err)
|
||||
assert.True(t, cmdutil.IsAuthError(err))
|
||||
}
|
||||
|
||||
+11
-10
@@ -9,8 +9,8 @@ import (
|
||||
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
||||
)
|
||||
|
||||
// authTokenFields lists fields available for `auth token --json=` projection.
|
||||
// Single-resource shape: filter applies to the bare token object directly.
|
||||
// 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"}
|
||||
|
||||
type tokenResult struct {
|
||||
@@ -30,7 +30,7 @@ type tokenResult struct {
|
||||
// `auth list` shows which mode each context uses.
|
||||
//
|
||||
// Default output: raw token on stdout, no trailing newline (clean $(...)).
|
||||
// `--json[=fields]` emits a bare {token, mode, context} object.
|
||||
// `--format json[=fields]` emits a bare {token, mode, context} object.
|
||||
func NewCmdToken(f *cmdutil.Factory) *cobra.Command {
|
||||
cmd := &cobra.Command{
|
||||
Use: "token",
|
||||
@@ -48,21 +48,22 @@ to see which mode each context uses, and construct the matching HTTP header:
|
||||
` + "`--context <name>`" + ` (global flag) selects a non-active context to read from.`,
|
||||
Example: ` WEKNORA_TOKEN=$(weknora auth token)
|
||||
weknora auth token --context staging
|
||||
weknora auth token --json`,
|
||||
weknora auth token --format json`,
|
||||
Args: cobra.NoArgs,
|
||||
RunE: func(c *cobra.Command, _ []string) error {
|
||||
jopts, err := cmdutil.CheckJSONFlags(c)
|
||||
fopts, err := cmdutil.CheckFormatFlag(c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return runToken(f, jopts)
|
||||
fopts.ResolveDefault(iostreams.IO.IsStdoutTTY())
|
||||
return runToken(f, fopts)
|
||||
},
|
||||
}
|
||||
cmdutil.AddJSONFlags(cmd, authTokenFields)
|
||||
cmdutil.AddFormatFlag(cmd, authTokenFields...)
|
||||
return cmd
|
||||
}
|
||||
|
||||
func runToken(f *cmdutil.Factory, jopts *cmdutil.JSONOptions) error {
|
||||
func runToken(f *cmdutil.Factory, fopts *cmdutil.FormatOptions) error {
|
||||
cfg, err := f.Config()
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -113,8 +114,8 @@ func runToken(f *cmdutil.Factory, jopts *cmdutil.JSONOptions) error {
|
||||
fmt.Sprintf("context %q credential is empty in keyring; run `weknora auth login`", ctxName))
|
||||
}
|
||||
|
||||
if jopts.Enabled() {
|
||||
return jopts.Emit(iostreams.IO.Out, tokenResult{Token: token, Mode: mode, Context: ctxName})
|
||||
if fopts.WantsJSON() {
|
||||
return fopts.Emit(iostreams.IO.Out, tokenResult{Token: token, Mode: mode, Context: ctxName})
|
||||
}
|
||||
|
||||
// No trailing newline - clean $(weknora auth token) substitution.
|
||||
|
||||
+15
-15
@@ -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), nil)
|
||||
err := runToken(tokenTestFactory(t, cfg, store), &cmdutil.FormatOptions{Mode: cmdutil.FormatText})
|
||||
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), nil); err != nil {
|
||||
if err := runToken(tokenTestFactory(t, cfg, store), &cmdutil.FormatOptions{Mode: cmdutil.FormatText}); err != nil {
|
||||
t.Fatalf("runToken: %v", err)
|
||||
}
|
||||
if got := out.String(); got != "sk_test_apikey_42" {
|
||||
@@ -77,7 +77,7 @@ func TestAuthToken_JSON(t *testing.T) {
|
||||
_ = store.Set("prod", "access", "jwt-xyz")
|
||||
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
if err := runToken(tokenTestFactory(t, cfg, store), &cmdutil.JSONOptions{}); err != nil {
|
||||
if err := runToken(tokenTestFactory(t, cfg, store), &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}); err != nil {
|
||||
t.Fatalf("runToken: %v", err)
|
||||
}
|
||||
var got struct {
|
||||
@@ -93,7 +93,7 @@ func TestAuthToken_JSON(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthToken_JSON_FieldFilter(t *testing.T) {
|
||||
func TestAuthToken_JSON_JQProjection(t *testing.T) {
|
||||
cfg := &config.Config{
|
||||
CurrentContext: "ci",
|
||||
Contexts: map[string]config.Context{
|
||||
@@ -104,8 +104,8 @@ func TestAuthToken_JSON_FieldFilter(t *testing.T) {
|
||||
_ = store.Set("ci", "api_key", "sk_42")
|
||||
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
jopts := &cmdutil.JSONOptions{Fields: []string{"token"}}
|
||||
if err := runToken(tokenTestFactory(t, cfg, store), jopts); err != nil {
|
||||
fopts := &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON, JQ: "{token}"}
|
||||
if err := runToken(tokenTestFactory(t, cfg, store), fopts); err != nil {
|
||||
t.Fatalf("runToken: %v", err)
|
||||
}
|
||||
var got map[string]any
|
||||
@@ -124,7 +124,7 @@ func TestAuthToken_NoCurrentContext(t *testing.T) {
|
||||
cfg := &config.Config{}
|
||||
store := secrets.NewMemStore()
|
||||
iostreams.SetForTest(t)
|
||||
err := runToken(tokenTestFactory(t, cfg, store), nil)
|
||||
err := runToken(tokenTestFactory(t, cfg, store), &cmdutil.FormatOptions{Mode: cmdutil.FormatText})
|
||||
if err == nil {
|
||||
t.Fatal("expected error, got nil")
|
||||
}
|
||||
@@ -149,7 +149,7 @@ func TestAuthToken_ContextOverride(t *testing.T) {
|
||||
f.ContextOverride = "staging"
|
||||
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
if err := runToken(f, nil); err != nil {
|
||||
if err := runToken(f, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}); err != nil {
|
||||
t.Fatalf("runToken: %v", err)
|
||||
}
|
||||
if got := out.String(); got != "staging-key" {
|
||||
@@ -167,7 +167,7 @@ func TestAuthToken_NoStoredCredential(t *testing.T) {
|
||||
store := secrets.NewMemStore()
|
||||
// no Set - keyring is empty
|
||||
iostreams.SetForTest(t)
|
||||
err := runToken(tokenTestFactory(t, cfg, store), nil)
|
||||
err := runToken(tokenTestFactory(t, cfg, store), &cmdutil.FormatOptions{Mode: cmdutil.FormatText})
|
||||
if err == nil {
|
||||
t.Fatal("expected auth.unauthenticated, got nil")
|
||||
}
|
||||
@@ -185,7 +185,7 @@ func TestAuthToken_ContextWithNoCredentialRefs(t *testing.T) {
|
||||
}
|
||||
store := secrets.NewMemStore()
|
||||
iostreams.SetForTest(t)
|
||||
err := runToken(tokenTestFactory(t, cfg, store), nil)
|
||||
err := runToken(tokenTestFactory(t, cfg, store), &cmdutil.FormatOptions{Mode: cmdutil.FormatText})
|
||||
if err == nil {
|
||||
t.Fatal("expected auth.unauthenticated, got nil")
|
||||
}
|
||||
@@ -229,7 +229,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), nil); err != nil {
|
||||
if err := runToken(tokenTestFactory(t, cfg, store), &cmdutil.FormatOptions{Mode: cmdutil.FormatText}); err != nil {
|
||||
t.Fatalf("runToken: %v", err)
|
||||
}
|
||||
if out.String() != "jwt-xyz" {
|
||||
@@ -243,7 +243,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), nil); err != nil {
|
||||
if err := runToken(tokenTestFactory(t, cfg, store), &cmdutil.FormatOptions{Mode: cmdutil.FormatText}); err != nil {
|
||||
t.Fatalf("runToken: %v", err)
|
||||
}
|
||||
if out.String() != "jwt-xyz" {
|
||||
@@ -260,7 +260,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), nil); err != nil {
|
||||
if err := runToken(tokenTestFactory(t, cfg, store), &cmdutil.FormatOptions{Mode: cmdutil.FormatText}); err != nil {
|
||||
t.Fatalf("runToken: %v", err)
|
||||
}
|
||||
if out.String() != "sk_42" {
|
||||
@@ -276,12 +276,12 @@ func TestAuthToken_TTY_APIKeyMode_IncludesRotationNote(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestAuthToken_TTY_JSONMode_NoStderrHint(t *testing.T) {
|
||||
// --json output mode targets script/agent consumers even when stdout
|
||||
// --format json output mode targets script/agent consumers even when stdout
|
||||
// happens to be a TTY (e.g. an IDE running the CLI on the user's
|
||||
// behalf). Hint would pollute their parsing - suppress.
|
||||
cfg, store := makeBearerCfg()
|
||||
_, errBuf := iostreams.SetForTestWithTTY(t)
|
||||
if err := runToken(tokenTestFactory(t, cfg, store), &cmdutil.JSONOptions{}); err != nil {
|
||||
if err := runToken(tokenTestFactory(t, cfg, store), &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}); err != nil {
|
||||
t.Fatalf("runToken: %v", err)
|
||||
}
|
||||
if errBuf.Len() != 0 {
|
||||
|
||||
Reference in New Issue
Block a user