feat(cli): --json field-select, --jq, auth token, doc --from-url

Output ergonomics:
- `--json` accepts a comma-separated field list (gh-parity); selects
  named keys from the per-command payload. Bare `--json` keeps the
  full shape.
- `--jq <expr>` evaluates a gojq expression over the JSON; pairs with
  `--json field-list` so projection runs before jq.
- `--version` is a global cobra flag in addition to the `version`
  subcommand; both render the same line.
- Per-command `--help` now renders the available JSON field list under
  "JSON fields available via `--json id,name,...`" (field-discovery
  parity with gh / kubectl `-o jsonpath`).

New commands:
- `auth token` — print the active context's credential to stdout for
  shell command substitution (`WEKNORA_TOKEN=$(weknora auth token)`).
  Default: raw secret, no trailing newline. `--json` emits
  `{token, mode, context}`.
- `doc upload --from-url <URL>` — ingest a remote URL via the SDK
  `CreateKnowledgeFromURL`. `--name` forwarded as `FileName` so the
  server's known-extension heuristic upgrades crawl-mode to
  file-download-mode where appropriate.

Includes the simplify post-review polish pass (field-filter unit
tests, --json/--jq compose check, agent_help copy fixes).
This commit is contained in:
nullkey
2026-05-14 23:28:14 +08:00
committed by lyingbug
parent 4fb089d4d7
commit 1b20b06f5e
81 changed files with 2351 additions and 642 deletions
+28 -1
View File
@@ -1,5 +1,5 @@
// Package auth holds the cobra commands for authentication
// (login / logout / list / refresh / status).
// (login / logout / list / refresh / status / token).
package auth
import (
@@ -8,6 +8,32 @@ import (
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
)
// Credential-mode tokens used in the JSON envelope of auth list / login /
// status / token. The string names describe the HTTP credential type rather
// than the login flow (e.g. JWT → bearer regardless of whether it was
// obtained via password or refresh) so an agent can branch directly on the
// header to construct: `Authorization: Bearer <token>` (ModeBearer) or
// `X-API-Key: <token>` (ModeAPIKey).
const (
ModeBearer = "bearer"
ModeAPIKey = "api-key"
ModeUnknown = "unknown"
)
// modeFromRefs maps the per-context TokenRef / APIKeyRef presence to a
// canonical credential-mode token. Bearer wins when both are present —
// matches the precedence in cmdutil.buildClient.
func modeFromRefs(apiKeyRef, tokenRef string) string {
switch {
case tokenRef != "":
return ModeBearer
case apiKeyRef != "":
return ModeAPIKey
default:
return ModeUnknown
}
}
// NewCmdAuth builds the `weknora auth` command tree and registers its
// subcommands. Called from cli/cmd/root.go.
func NewCmdAuth(f *cmdutil.Factory) *cobra.Command {
@@ -27,5 +53,6 @@ func NewCmdAuth(f *cmdutil.Factory) *cobra.Command {
cmd.AddCommand(NewCmdList(f))
cmd.AddCommand(NewCmdRefresh(f))
cmd.AddCommand(NewCmdStatus(f))
cmd.AddCommand(NewCmdToken(f))
return cmd
}
+3 -4
View File
@@ -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.Factory, _ LoginService) error {
cmd := NewCmdLogin(f, func(_ context.Context, opts *LoginOptions, _ *cmdutil.JSONOptions, _ *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, f))
require.NoError(t, persistAPIKey(opts, &cmdutil.JSONOptions{}, f))
v, _ := store.Get("ci", "api_key")
assert.Equal(t, "sk-zzz", v)
cfg, _ := f.Config()
@@ -98,14 +98,13 @@ func TestPersistJWT_StoresBothTokens(t *testing.T) {
opts := &LoginOptions{
Host: "https://x",
Context: "p",
JSONOut: true,
}
resp := &sdk.LoginResponse{
Token: "jwt-acc",
RefreshToken: "jwt-ref",
User: &sdk.AuthUser{Email: "a@b.c", TenantID: 7},
}
require.NoError(t, persistJWT(opts, f, resp))
require.NoError(t, persistJWT(opts, &cmdutil.JSONOptions{}, f, resp))
a, _ := store.Get("p", "access")
r, _ := store.Get("p", "refresh")
assert.Equal(t, "jwt-acc", a)
+19 -25
View File
@@ -13,15 +13,19 @@ import (
"github.com/Tencent/WeKnora/cli/internal/iostreams"
)
type ListOptions struct {
JSONOut bool
type ListOptions struct{}
// authListFields enumerates the fields surfaced for `--json` discovery on
// `auth list`. Each entry is a per-context summary row.
var authListFields = []string{
"name", "host", "user", "mode", "current",
}
type listEntry struct {
Name string `json:"name"`
Host string `json:"host"`
User string `json:"user,omitempty"`
Mode string `json:"mode"` // "api-key" / "password" / "unknown"
Mode string `json:"mode"` // ModeBearer / ModeAPIKey / ModeUnknown
Current bool `json:"current"`
}
@@ -29,21 +33,24 @@ type listEntry struct {
// row per registered context, marking the active one. Reads only
// ~/.config/weknora/config.yaml — no network, no keyring touch.
func NewCmdList(f *cmdutil.Factory) *cobra.Command {
opts := &ListOptions{}
cmd := &cobra.Command{
Use: "list",
Short: "List configured authentication contexts",
Args: cobra.NoArgs,
RunE: func(c *cobra.Command, _ []string) error {
return runList(opts, f)
jopts, err := cmdutil.CheckJSONFlags(c)
if err != nil {
return err
}
return runList(jopts, f)
},
}
cmd.Flags().BoolVar(&opts.JSONOut, "json", false, "Output JSON envelope")
cmdutil.AddJSONFlags(cmd, authListFields)
agent.SetAgentHelp(cmd, "Lists configured auth contexts (name/host/user/mode/current). Read-only, no network, no keyring access. Use to confirm context names before --context or `auth login --name`.")
return cmd
}
func runList(opts *ListOptions, f *cmdutil.Factory) error {
func runList(jopts *cmdutil.JSONOptions, f *cmdutil.Factory) error {
cfg, err := f.Config()
if err != nil {
return err
@@ -54,15 +61,16 @@ func runList(opts *ListOptions, f *cmdutil.Factory) error {
Name: name,
Host: c.Host,
User: c.User,
Mode: inferMode(c.APIKeyRef, c.TokenRef),
Mode: modeFromRefs(c.APIKeyRef, c.TokenRef),
Current: name == cfg.CurrentContext,
})
}
sort.Slice(entries, func(i, j int) bool { return entries[i].Name < entries[j].Name })
if opts.JSONOut {
return cmdutil.NewJSONExporter().Write(iostreams.IO.Out,
format.Success(entries, &format.Meta{Context: cfg.CurrentContext}))
if jopts.Enabled() {
return format.WriteEnvelopeFiltered(iostreams.IO.Out,
format.Success(entries, &format.Meta{Context: cfg.CurrentContext}),
jopts.Fields, jopts.JQ)
}
if len(entries) == 0 {
fmt.Fprintln(iostreams.IO.Out, "No contexts configured. Run `weknora auth login` to create one.")
@@ -80,17 +88,3 @@ func runList(opts *ListOptions, f *cmdutil.Factory) error {
return tw.Flush()
}
// inferMode reports which credential shape the context was logged in with.
// A context with both refs set (which shouldn't happen with the current
// login flow but might appear in hand-edited configs) is treated as
// password — JWT wins because it's the more capable mode.
func inferMode(apiKeyRef, tokenRef string) string {
switch {
case tokenRef != "":
return "password"
case apiKeyRef != "":
return "api-key"
default:
return "unknown"
}
}
+14 -14
View File
@@ -28,15 +28,15 @@ func TestList_HumanRender(t *testing.T) {
"staging": {Host: "https://staging", APIKeyRef: "keychain://staging/api_key"},
},
}
require.NoError(t, runList(&ListOptions{}, newListFactory(cfg)))
require.NoError(t, runList(nil, newListFactory(cfg)))
got := out.String()
// One row per context, current marked with `*`.
assert.Contains(t, got, "* prod")
assert.Contains(t, got, " staging")
// Mode column.
assert.Contains(t, got, "password")
assert.Contains(t, got, "api-key")
assert.Contains(t, got, ModeBearer)
assert.Contains(t, got, ModeAPIKey)
// Sorted alphabetically — prod after staging? No: "prod" < "staging".
assert.Less(t, strings.Index(got, "prod"), strings.Index(got, "staging"),
"contexts should render sorted by name")
@@ -44,7 +44,7 @@ func TestList_HumanRender(t *testing.T) {
func TestList_Empty(t *testing.T) {
out, _ := iostreams.SetForTest(t)
require.NoError(t, runList(&ListOptions{}, newListFactory(&config.Config{})))
require.NoError(t, runList(nil, newListFactory(&config.Config{})))
assert.Contains(t, out.String(), "No contexts configured")
}
@@ -57,7 +57,7 @@ func TestList_JSONEnvelope(t *testing.T) {
"staging": {Host: "https://staging", APIKeyRef: "key"},
},
}
require.NoError(t, runList(&ListOptions{JSONOut: true}, newListFactory(cfg)))
require.NoError(t, runList(&cmdutil.JSONOptions{}, newListFactory(cfg)))
var env struct {
OK bool `json:"ok"`
@@ -73,17 +73,17 @@ func TestList_JSONEnvelope(t *testing.T) {
// Sorted: prod < staging.
assert.Equal(t, "prod", env.Data[0].Name)
assert.True(t, env.Data[0].Current)
assert.Equal(t, "password", env.Data[0].Mode)
assert.Equal(t, ModeBearer, env.Data[0].Mode)
assert.Equal(t, "staging", env.Data[1].Name)
assert.False(t, env.Data[1].Current)
assert.Equal(t, "api-key", env.Data[1].Mode)
assert.Equal(t, ModeAPIKey, env.Data[1].Mode)
}
func TestList_InferModeUnknown(t *testing.T) {
// Hand-edited config with neither ref set — surface "unknown" rather than
// pretending the context is a valid login.
assert.Equal(t, "unknown", inferMode("", ""))
assert.Equal(t, "password", inferMode("", "tok"))
assert.Equal(t, "api-key", inferMode("key", ""))
assert.Equal(t, "password", inferMode("key", "tok"), "JWT wins when both set")
func TestModeFromRefs(t *testing.T) {
// Hand-edited config with neither ref set — surface "unknown" rather
// than pretending the context is a valid login.
assert.Equal(t, ModeUnknown, modeFromRefs("", ""))
assert.Equal(t, ModeBearer, modeFromRefs("", "tok"))
assert.Equal(t, ModeAPIKey, modeFromRefs("key", ""))
assert.Equal(t, ModeBearer, modeFromRefs("key", "tok"), "JWT wins when both set")
}
+33 -20
View File
@@ -16,6 +16,14 @@ import (
sdk "github.com/Tencent/WeKnora/client"
)
// authLoginFields enumerates the fields surfaced for `--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`.
var authLoginFields = []string{
"context", "host", "mode", "user", "tenant_id",
}
// LoginOptions is the configuration captured from flags + prompts.
type LoginOptions struct {
Host string // --host
@@ -24,7 +32,6 @@ type LoginOptions struct {
APIKey string // populated by --with-token from stdin
Email string
Password string
JSONOut bool
StdinReader io.Reader // override for tests
}
@@ -37,7 +44,7 @@ type LoginService interface {
// 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.Factory, LoginService) error) *cobra.Command {
func NewCmdLogin(f *cmdutil.Factory, runF func(context.Context, *LoginOptions, *cmdutil.JSONOptions, *cmdutil.Factory, LoginService) error) *cobra.Command {
opts := &LoginOptions{}
cmd := &cobra.Command{
Use: "login",
@@ -49,6 +56,10 @@ 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)
if err != nil {
return err
}
run := runF
if run == nil {
run = runLogin
@@ -57,13 +68,13 @@ the current_context in ~/.config/weknora/config.yaml.`,
if opts.StdinReader == nil {
opts.StdinReader = iostreams.IO.In
}
return run(c.Context(), opts, f, svc)
return run(c.Context(), opts, jopts, 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")
cmd.Flags().BoolVar(&opts.JSONOut, "json", false, "Output JSON envelope")
cmdutil.AddJSONFlags(cmd, authLoginFields)
cmdutil.MustRequireFlag(cmd, "host")
agent.SetAgentHelp(cmd, "Authenticates and stores credentials. --with-token reads an API key from stdin (no password prompt, agent-safe). Otherwise email/password prompts fire — non-TTY callers must pipe `--with-token` or pre-set --name. Errors: auth.bad_credential on wrong password; input.invalid_argument on bad --host; input.missing_flag when --with-token has empty stdin.")
return cmd
@@ -78,7 +89,7 @@ func loginServiceFor(host string) LoginService {
return sdk.NewClient(host)
}
func runLogin(ctx context.Context, opts *LoginOptions, f *cmdutil.Factory, svc LoginService) error {
func runLogin(ctx context.Context, opts *LoginOptions, jopts *cmdutil.JSONOptions, f *cmdutil.Factory, svc LoginService) error {
if err := validateHost(opts.Host); err != nil {
return err
}
@@ -92,7 +103,7 @@ func runLogin(ctx context.Context, opts *LoginOptions, f *cmdutil.Factory, svc L
return cmdutil.NewError(cmdutil.CodeInputMissingFlag, "--with-token requires an API key piped to stdin")
}
opts.APIKey = key
return persistAPIKey(opts, f)
return persistAPIKey(opts, jopts, f)
}
// Interactive: prompt for email + password.
@@ -125,11 +136,11 @@ func runLogin(ctx context.Context, opts *LoginOptions, f *cmdutil.Factory, svc L
return cmdutil.NewError(cmdutil.CodeAuthBadCredential, fmt.Sprintf("login refused: %s", resp.Message))
}
return persistJWT(opts, f, resp)
return persistJWT(opts, jopts, f, resp)
}
// persistAPIKey saves the --with-token API key and writes the context.
func persistAPIKey(opts *LoginOptions, f *cmdutil.Factory) error {
func persistAPIKey(opts *LoginOptions, jopts *cmdutil.JSONOptions, f *cmdutil.Factory) error {
store, err := f.Secrets()
if err != nil {
return err
@@ -137,14 +148,14 @@ func persistAPIKey(opts *LoginOptions, f *cmdutil.Factory) error {
if err := store.Set(opts.Context, "api_key", opts.APIKey); err != nil {
return cmdutil.Wrapf(cmdutil.CodeLocalKeychainDenied, err, "save api key")
}
return saveContextRef(opts, f, &config.Context{
return saveContextRef(opts, jopts, f, &config.Context{
Host: opts.Host,
APIKeyRef: store.Ref(opts.Context, "api_key"),
}, nil)
}
// persistJWT saves access + refresh tokens and writes the context.
func persistJWT(opts *LoginOptions, f *cmdutil.Factory, resp *sdk.LoginResponse) error {
func persistJWT(opts *LoginOptions, jopts *cmdutil.JSONOptions, f *cmdutil.Factory, resp *sdk.LoginResponse) error {
store, err := f.Secrets()
if err != nil {
return err
@@ -166,7 +177,7 @@ func persistJWT(opts *LoginOptions, f *cmdutil.Factory, resp *sdk.LoginResponse)
c.User = resp.User.Email
c.TenantID = resp.User.TenantID
}
return saveContextRef(opts, f, c, resp.User)
return saveContextRef(opts, jopts, f, c, resp.User)
}
// loginResult is the typed payload emitted by `--json`. mode is derived from
@@ -174,13 +185,13 @@ func persistJWT(opts *LoginOptions, f *cmdutil.Factory, resp *sdk.LoginResponse)
type loginResult struct {
Context string `json:"context"`
Host string `json:"host"`
Mode string `json:"mode"` // "password" or "api-key"
Mode string `json:"mode"` // ModeBearer or ModeAPIKey
User string `json:"user,omitempty"`
TenantID uint64 `json:"tenant_id,omitempty"`
}
// saveContextRef writes the context to config.yaml and prints success.
func saveContextRef(opts *LoginOptions, f *cmdutil.Factory, ctx *config.Context, user *sdk.AuthUser) error {
func saveContextRef(opts *LoginOptions, jopts *cmdutil.JSONOptions, f *cmdutil.Factory, ctx *config.Context, user *sdk.AuthUser) error {
cfg, err := f.Config()
if err != nil {
return err
@@ -193,17 +204,19 @@ func saveContextRef(opts *LoginOptions, f *cmdutil.Factory, ctx *config.Context,
if err := config.Save(cfg); err != nil {
return cmdutil.Wrapf(cmdutil.CodeLocalFileIO, err, "save config")
}
if opts.JSONOut {
result := loginResult{Context: opts.Context, Host: opts.Host, Mode: "api-key"}
if jopts.Enabled() {
result := loginResult{Context: opts.Context, Host: opts.Host, Mode: ModeAPIKey}
if user != nil {
result.Mode = "password"
result.Mode = ModeBearer
result.User = user.Email
result.TenantID = user.TenantID
}
return cmdutil.NewJSONExporter().Write(iostreams.IO.Out, format.Success(result, &format.Meta{
Context: opts.Context,
TenantID: ctx.TenantID,
}))
return format.WriteEnvelopeFiltered(iostreams.IO.Out,
format.Success(result, &format.Meta{
Context: opts.Context,
TenantID: ctx.TenantID,
}),
jopts.Fields, jopts.JQ)
}
who := opts.Context
if user != nil {
+5 -5
View File
@@ -61,7 +61,7 @@ func TestRunLogin_PasswordMode(t *testing.T) {
Host: "https://kb.example.com",
Context: "prod",
}
require.NoError(t, runLogin(context.Background(), opts, f, svc))
require.NoError(t, runLogin(context.Background(), opts, nil, f, svc))
assert.Equal(t, "a@b.c", svc.got.email)
assert.Equal(t, "secret", svc.got.password)
@@ -79,7 +79,7 @@ func TestRunLogin_WithToken(t *testing.T) {
WithToken: true,
StdinReader: strings.NewReader(" sk-1234 \n"),
}
require.NoError(t, runLogin(context.Background(), opts, f, nil))
require.NoError(t, runLogin(context.Background(), opts, nil, f, nil))
got, _ := store.Get("ci", "api_key")
assert.Equal(t, "sk-1234", got)
}
@@ -93,7 +93,7 @@ func TestRunLogin_WithToken_Empty(t *testing.T) {
WithToken: true,
StdinReader: strings.NewReader(""),
}
err := runLogin(context.Background(), opts, f, nil)
err := runLogin(context.Background(), opts, nil, f, nil)
require.Error(t, err)
assert.Contains(t, err.Error(), "input.missing_flag")
}
@@ -101,7 +101,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"}, f, nil)
err := runLogin(context.Background(), &LoginOptions{Host: "ftp://nope"}, nil, f, nil)
require.Error(t, err)
assert.Contains(t, err.Error(), "input.invalid_argument")
}
@@ -110,7 +110,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"}, f, svc)
err := runLogin(context.Background(), &LoginOptions{Host: "https://x", Context: "p"}, nil, f, svc)
require.Error(t, err)
assert.Contains(t, err.Error(), "auth.bad_credential")
}
+18 -9
View File
@@ -15,11 +15,15 @@ import (
)
type LogoutOptions struct {
Name string // --name: target a specific context (default: current)
All bool // --all: clear every context
JSONOut bool
Name string // --name: target a specific context (default: current)
All bool // --all: clear every context
}
// authLogoutFields enumerates the fields surfaced for `--json` discovery
// on `auth logout`. The result is the list of context names that were
// logged out.
var authLogoutFields = []string{"removed"}
// logoutResult is the typed payload emitted under data.
type logoutResult struct {
Removed []string `json:"removed"`
@@ -44,18 +48,22 @@ accepted until it expires.`,
weknora auth logout --all`,
Args: cobra.NoArgs,
RunE: func(c *cobra.Command, _ []string) error {
return runLogout(opts, f)
jopts, err := cmdutil.CheckJSONFlags(c)
if err != nil {
return err
}
return runLogout(opts, jopts, 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().BoolVar(&opts.JSONOut, "json", false, "Output JSON envelope")
cmdutil.AddJSONFlags(cmd, authLogoutFields)
cmd.MarkFlagsMutuallyExclusive("name", "all")
agent.SetAgentHelp(cmd, "Clears local credentials only; the server-side token / api-key continues to be valid until expired or rotated. Returns data.removed: [...names]. Errors: auth.unauthenticated when no contexts configured.")
return cmd
}
func runLogout(opts *LogoutOptions, f *cmdutil.Factory) error {
func runLogout(opts *LogoutOptions, jopts *cmdutil.JSONOptions, f *cmdutil.Factory) error {
cfg, err := f.Config()
if err != nil {
return err
@@ -88,9 +96,10 @@ func runLogout(opts *LogoutOptions, f *cmdutil.Factory) error {
return cmdutil.Wrapf(cmdutil.CodeLocalFileIO, err, "save config")
}
if opts.JSONOut {
return cmdutil.NewJSONExporter().Write(iostreams.IO.Out,
format.Success(logoutResult{Removed: targets}, nil))
if jopts.Enabled() {
return format.WriteEnvelopeFiltered(iostreams.IO.Out,
format.Success(logoutResult{Removed: targets}, nil),
jopts.Fields, jopts.JQ)
}
fmt.Fprintf(iostreams.IO.Out, "✓ Logged out of %d context(s): %s\n", len(targets), strings.Join(targets, ", "))
return nil
+6 -6
View File
@@ -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{}, newLogoutFactory(t, cfg, store)))
require.NoError(t, runLogout(&LogoutOptions{}, nil, 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"}, newLogoutFactory(t, cfg, store)))
require.NoError(t, runLogout(&LogoutOptions{Name: "staging"}, nil, 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}, newLogoutFactory(t, cfg, store)))
require.NoError(t, runLogout(&LogoutOptions{All: true}, nil, 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{}, newLogoutFactory(t, cfg, secrets.NewMemStore()))
err := runLogout(&LogoutOptions{}, nil, 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"}, newLogoutFactory(t, cfg, secrets.NewMemStore()))
err := runLogout(&LogoutOptions{Name: "ghost"}, nil, 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{}, newLogoutFactory(t, cfg, secrets.NewMemStore()))
err := runLogout(&LogoutOptions{}, nil, newLogoutFactory(t, cfg, secrets.NewMemStore()))
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
+16 -8
View File
@@ -14,10 +14,13 @@ import (
)
type RefreshOptions struct {
Name string // --name: target context (defaults to current)
JSONOut bool
Name string // --name: target context (defaults to current)
}
// authRefreshFields enumerates the fields surfaced for `--json` discovery
// on `auth refresh`. Token values are intentionally omitted — see refreshResult.
var authRefreshFields = []string{"context"}
// 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
@@ -47,11 +50,15 @@ 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 {
return runRefresh(c.Context(), opts, f, defaultRefresher)
jopts, err := cmdutil.CheckJSONFlags(c)
if err != nil {
return err
}
return runRefresh(c.Context(), opts, jopts, f, defaultRefresher)
},
}
cmd.Flags().StringVar(&opts.Name, "name", "", "Context to refresh (defaults to the current context)")
cmd.Flags().BoolVar(&opts.JSONOut, "json", false, "Output JSON envelope")
cmdutil.AddJSONFlags(cmd, authRefreshFields)
agent.SetAgentHelp(cmd, "Renews the access token using the stored refresh token. Errors with auth.token_expired when refresh itself is rejected — surface the hint to re-run auth login.")
return cmd
}
@@ -63,7 +70,7 @@ func defaultRefresher(host string) cmdutil.Refresher {
return sdk.NewClient(host)
}
func runRefresh(ctx context.Context, opts *RefreshOptions, f *cmdutil.Factory, refresherFor func(host string) cmdutil.Refresher) error {
func runRefresh(ctx context.Context, opts *RefreshOptions, jopts *cmdutil.JSONOptions, f *cmdutil.Factory, refresherFor func(host string) cmdutil.Refresher) error {
cfg, err := f.Config()
if err != nil {
return err
@@ -105,9 +112,10 @@ func runRefresh(ctx context.Context, opts *RefreshOptions, f *cmdutil.Factory, r
return err
}
if opts.JSONOut {
return format.WriteEnvelope(iostreams.IO.Out,
format.Success(refreshResult{Context: name}, &format.Meta{Context: name}))
if jopts.Enabled() {
return format.WriteEnvelopeFiltered(iostreams.IO.Out,
format.Success(refreshResult{Context: name}, &format.Meta{Context: name}),
jopts.Fields, jopts.JQ)
}
fmt.Fprintf(iostreams.IO.Out, "✓ Refreshed access token for context %s\n", name)
return nil
+8 -8
View File
@@ -73,7 +73,7 @@ func TestRefresh_Happy(t *testing.T) {
AccessToken: "new-access",
RefreshToken: "new-refresh",
}}
require.NoError(t, runRefresh(context.Background(), &RefreshOptions{}, f, stubSvc(svc)))
require.NoError(t, runRefresh(context.Background(), &RefreshOptions{}, nil, f, stubSvc(svc)))
assert.Equal(t, "old-refresh", svc.gotTok, "must pass stored refresh token to SDK")
gotAccess, _ := store.Get("prod", "access")
@@ -98,7 +98,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"}, f, stubSvc(svc)))
require.NoError(t, runRefresh(context.Background(), &RefreshOptions{Name: "staging"}, nil, f, stubSvc(svc)))
assert.Equal(t, "stg-refresh", svc.gotTok, "--name=staging must refresh the staging context, not current")
// current is untouched
@@ -110,7 +110,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{}, f, stubSvc(&fakeRefreshService{}))
err := runRefresh(context.Background(), &RefreshOptions{}, nil, f, stubSvc(&fakeRefreshService{}))
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
@@ -126,7 +126,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{}, f, stubSvc(&fakeRefreshService{}))
err := runRefresh(context.Background(), &RefreshOptions{}, nil, f, stubSvc(&fakeRefreshService{}))
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
@@ -144,7 +144,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{}, f, stubSvc(&fakeRefreshService{}))
err := runRefresh(context.Background(), &RefreshOptions{}, nil, f, stubSvc(&fakeRefreshService{}))
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
@@ -162,7 +162,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{}, f, stubSvc(svc))
err := runRefresh(context.Background(), &RefreshOptions{}, nil, f, stubSvc(svc))
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
@@ -185,7 +185,7 @@ func TestRefresh_TransportError(t *testing.T) {
}
f := newRefreshFactory(t, cfg, store)
svc := &fakeRefreshService{err: errors.New("connection reset")}
err := runRefresh(context.Background(), &RefreshOptions{}, f, stubSvc(svc))
err := runRefresh(context.Background(), &RefreshOptions{}, nil, f, stubSvc(svc))
require.Error(t, err)
var typed *cmdutil.Error
require.ErrorAs(t, err, &typed)
@@ -205,7 +205,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{JSONOut: true}, f, stubSvc(svc)))
require.NoError(t, runRefresh(context.Background(), &RefreshOptions{}, &cmdutil.JSONOptions{}, f, stubSvc(svc)))
var env format.Envelope
require.NoError(t, json.Unmarshal(out.Bytes(), &env))
+18 -11
View File
@@ -13,8 +13,10 @@ import (
sdk "github.com/Tencent/WeKnora/client"
)
type StatusOptions struct {
JSONOut bool
// authStatusFields enumerates the fields surfaced for `--json` discovery
// on `auth status`. Single-resource shape: filter applies to data itself.
var authStatusFields = []string{
"context", "user_id", "email", "tenant_id", "tenant_name",
}
// StatusService is the narrow SDK surface auth status depends on.
@@ -33,25 +35,28 @@ type statusResult struct {
// NewCmdStatus builds the `weknora auth status` command.
func NewCmdStatus(f *cmdutil.Factory) *cobra.Command {
opts := &StatusOptions{}
cmd := &cobra.Command{
Use: "status",
Short: "Show the active context, principal, and token state",
Args: cobra.NoArgs,
RunE: func(c *cobra.Command, args []string) error {
jopts, err := cmdutil.CheckJSONFlags(c)
if err != nil {
return err
}
cli, err := f.Client()
if err != nil {
return err
}
return runStatus(c.Context(), opts, f, cli)
return runStatus(c.Context(), jopts, f, cli)
},
}
cmd.Flags().BoolVar(&opts.JSONOut, "json", false, "Output JSON envelope")
cmdutil.AddJSONFlags(cmd, authStatusFields)
agent.SetAgentHelp(cmd, "Live-checks the active credential by calling /auth/me. Returns {context, user_id, email, tenant_id, tenant_name}. Errors: auth.unauthenticated when token is invalid or missing (run `auth login` / `auth refresh`).")
return cmd
}
func runStatus(ctx context.Context, opts *StatusOptions, f *cmdutil.Factory, svc StatusService) error {
func runStatus(ctx context.Context, jopts *cmdutil.JSONOptions, f *cmdutil.Factory, svc StatusService) error {
if svc == nil {
return cmdutil.NewError(cmdutil.CodeAuthUnauthenticated, "no SDK client available; run `weknora auth login`")
}
@@ -67,7 +72,7 @@ func runStatus(ctx context.Context, opts *StatusOptions, f *cmdutil.Factory, svc
return err
}
if opts.JSONOut {
if jopts.Enabled() {
var tenantID uint64
result := statusResult{Context: cfg.CurrentContext}
if user != nil {
@@ -79,10 +84,12 @@ func runStatus(ctx context.Context, opts *StatusOptions, f *cmdutil.Factory, svc
if tenant != nil {
result.TenantName = tenant.Name
}
return cmdutil.NewJSONExporter().Write(iostreams.IO.Out, format.Success(result, &format.Meta{
Context: cfg.CurrentContext,
TenantID: tenantID,
}))
return format.WriteEnvelopeFiltered(iostreams.IO.Out,
format.Success(result, &format.Meta{
Context: cfg.CurrentContext,
TenantID: tenantID,
}),
jopts.Fields, jopts.JQ)
}
host := ""
+5 -5
View File
@@ -52,7 +52,7 @@ func TestRunStatus_HumanOutput(t *testing.T) {
&sdk.AuthTenant{ID: 7, Name: "Acme"},
),
}
require.NoError(t, runStatus(context.Background(), &StatusOptions{}, f, svc))
require.NoError(t, runStatus(context.Background(), nil, f, svc))
got := out.String()
assert.Contains(t, got, "context: prod")
assert.Contains(t, got, "host: https://kb.example.com")
@@ -69,14 +69,14 @@ 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(), &StatusOptions{JSONOut: true}, f, svc))
require.NoError(t, runStatus(context.Background(), &cmdutil.JSONOptions{}, f, svc))
assert.True(t, strings.HasPrefix(out.String(), `{"ok":true`), "got: %q", out.String())
assert.Contains(t, out.String(), `"email":"a@b.c"`)
}
func TestRunStatus_NoSDKClient(t *testing.T) {
iostreams.SetForTest(t)
err := runStatus(context.Background(), &StatusOptions{}, &cmdutil.Factory{}, nil)
err := runStatus(context.Background(), nil, &cmdutil.Factory{}, nil)
require.Error(t, err)
assert.True(t, cmdutil.IsAuthError(err))
}
@@ -86,7 +86,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(), &StatusOptions{}, f, &fakeStatusService{err: assert.AnError})
err := runStatus(context.Background(), nil, 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.
@@ -98,7 +98,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(), &StatusOptions{}, f, &fakeStatusService{err: errors.New("HTTP error 401: invalid token")})
err := runStatus(context.Background(), nil, f, &fakeStatusService{err: errors.New("HTTP error 401: invalid token")})
require.Error(t, err)
assert.True(t, cmdutil.IsAuthError(err))
}
+129
View File
@@ -0,0 +1,129 @@
package auth
import (
"fmt"
"github.com/spf13/cobra"
"github.com/Tencent/WeKnora/cli/internal/agent"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/format"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
)
// authTokenFields lists fields available for `auth token --json=` projection.
// Single-resource envelope shape (data is the token result, not data.items).
var authTokenFields = []string{"token", "mode", "context"}
type tokenResult struct {
Token string `json:"token"`
Mode string `json:"mode"` // ModeBearer (JWT) or ModeAPIKey
Context string `json:"context"`
}
// NewCmdToken builds `weknora auth token`. Prints the active context's
// credential to stdout for use in shell pipelines, e.g.
//
// WEKNORA_TOKEN=$(weknora auth token)
// curl -H "Authorization: Bearer $WEKNORA_TOKEN" ... # JWT mode
// curl -H "X-API-Key: $WEKNORA_TOKEN" ... # api-key mode
//
// Mirrors gh's `gh auth token`. The user is responsible for constructing
// the appropriate header — `auth list` shows which mode each context uses.
//
// Default output: raw token on stdout, no trailing newline (clean $(...)).
// `--json[=fields]` wraps in envelope {token, mode, context}.
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
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:
Authorization: Bearer <token> # bearer mode
X-API-Key: <token> # api-key mode
` + "`--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`,
Args: cobra.NoArgs,
RunE: func(c *cobra.Command, _ []string) error {
jopts, err := cmdutil.CheckJSONFlags(c)
if err != nil {
return err
}
return runToken(f, jopts)
},
}
cmdutil.AddJSONFlags(cmd, authTokenFields)
agent.SetAgentHelp(cmd, "Prints the active context's credential to stdout for scripting. Default: raw secret, no trailing newline. With --json: envelope {token, mode, context}. Errors: auth.unauthenticated when no active context or no stored credential (run `auth login`); local.keychain_denied when the keyring rejects the read.")
return cmd
}
func runToken(f *cmdutil.Factory, jopts *cmdutil.JSONOptions) error {
cfg, err := f.Config()
if err != nil {
return err
}
ctxName := cfg.CurrentContext
if f.ContextOverride != "" {
ctxName = f.ContextOverride
}
if ctxName == "" {
return cmdutil.NewError(cmdutil.CodeAuthUnauthenticated,
"no current context configured")
}
ctx, ok := cfg.Contexts[ctxName]
if !ok {
return cmdutil.NewError(cmdutil.CodeLocalContextNotFound,
fmt.Sprintf("context %q not found", ctxName))
}
store, err := f.Secrets()
if err != nil {
return cmdutil.Wrapf(cmdutil.CodeLocalKeychainDenied, err, "init secrets store")
}
// Resolve the stored credential. Prefer bearer (JWT) when both refs
// are present — JWT is the more capable mode and what `buildClient`
// uses for the Authorization header (see factory.go buildClient).
var token, mode string
switch {
case ctx.TokenRef != "":
v, ferr := cmdutil.LoadSecret(store, ctxName, "access")
if ferr != nil {
return ferr
}
token, mode = v, ModeBearer
case ctx.APIKeyRef != "":
v, ferr := cmdutil.LoadSecret(store, ctxName, "api_key")
if ferr != nil {
return ferr
}
token, mode = v, ModeAPIKey
default:
return cmdutil.NewError(cmdutil.CodeAuthUnauthenticated,
fmt.Sprintf("context %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))
}
if jopts.Enabled() {
return format.WriteEnvelopeFiltered(iostreams.IO.Out,
format.Success(tokenResult{Token: token, Mode: mode, Context: ctxName},
&format.Meta{Context: ctxName}),
jopts.Fields, jopts.JQ)
}
// No trailing newline — clean $(weknora auth token) substitution.
fmt.Fprint(iostreams.IO.Out, token)
return nil
}
+203
View File
@@ -0,0 +1,203 @@
package auth
import (
"encoding/json"
"strings"
"testing"
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
"github.com/Tencent/WeKnora/cli/internal/config"
"github.com/Tencent/WeKnora/cli/internal/iostreams"
"github.com/Tencent/WeKnora/cli/internal/secrets"
)
// tokenTestFactory wires a config + in-memory secrets store the same way
// the production Factory does, so runToken exercises the real LoadSecret
// path.
func tokenTestFactory(t *testing.T, cfg *config.Config, store *secrets.MemStore) *cmdutil.Factory {
t.Helper()
f := &cmdutil.Factory{
Config: func() (*config.Config, error) { return cfg, nil },
Secrets: func() (secrets.Store, error) { return store, nil },
}
return f
}
func TestAuthToken_BearerMode_PlainOutput(t *testing.T) {
cfg := &config.Config{
CurrentContext: "prod",
Contexts: map[string]config.Context{
"prod": {Host: "https://kb.example.com", TokenRef: "prod:access", RefreshRef: "prod:refresh"},
},
}
store := secrets.NewMemStore()
_ = store.Set("prod", "access", "jwt-token-xyz")
out, _ := iostreams.SetForTest(t)
err := runToken(tokenTestFactory(t, cfg, store), nil)
if err != nil {
t.Fatalf("runToken: %v", err)
}
got := out.String()
if got != "jwt-token-xyz" {
t.Errorf("expected raw token, got %q", got)
}
if strings.HasSuffix(got, "\n") {
t.Errorf("output must NOT end with newline (clean $(...) substitution); got %q", got)
}
}
func TestAuthToken_APIKeyMode_PlainOutput(t *testing.T) {
cfg := &config.Config{
CurrentContext: "ci",
Contexts: map[string]config.Context{
"ci": {Host: "https://kb.example.com", APIKeyRef: "ci:api_key"},
},
}
store := secrets.NewMemStore()
_ = store.Set("ci", "api_key", "sk_test_apikey_42")
out, _ := iostreams.SetForTest(t)
if err := runToken(tokenTestFactory(t, cfg, store), nil); err != nil {
t.Fatalf("runToken: %v", err)
}
if got := out.String(); got != "sk_test_apikey_42" {
t.Errorf("expected api-key value, got %q", got)
}
}
func TestAuthToken_JSON(t *testing.T) {
cfg := &config.Config{
CurrentContext: "prod",
Contexts: map[string]config.Context{
"prod": {Host: "https://kb.example.com", TokenRef: "prod:access"},
},
}
store := secrets.NewMemStore()
_ = store.Set("prod", "access", "jwt-xyz")
out, _ := iostreams.SetForTest(t)
if err := runToken(tokenTestFactory(t, cfg, store), &cmdutil.JSONOptions{}); err != nil {
t.Fatalf("runToken: %v", err)
}
var env struct {
OK bool `json:"ok"`
Data struct {
Token string `json:"token"`
Mode string `json:"mode"`
Context string `json:"context"`
} `json:"data"`
}
if err := json.Unmarshal(out.Bytes(), &env); err != nil {
t.Fatalf("parse: %v\n%s", err, out.String())
}
if !env.OK {
t.Errorf("ok=false")
}
if env.Data.Token != "jwt-xyz" || env.Data.Mode != "bearer" || env.Data.Context != "prod" {
t.Errorf("envelope payload wrong: %+v", env.Data)
}
}
func TestAuthToken_JSON_FieldFilter(t *testing.T) {
cfg := &config.Config{
CurrentContext: "ci",
Contexts: map[string]config.Context{
"ci": {Host: "https://kb.example.com", APIKeyRef: "ci:api_key"},
},
}
store := secrets.NewMemStore()
_ = 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 {
t.Fatalf("runToken: %v", err)
}
var env struct {
Data map[string]any `json:"data"`
}
if err := json.Unmarshal(out.Bytes(), &env); err != nil {
t.Fatalf("parse: %v", err)
}
if _, has := env.Data["mode"]; has {
t.Errorf("mode should be filtered out: %+v", env.Data)
}
if env.Data["token"] != "sk_42" {
t.Errorf("token wrong: %+v", env.Data)
}
}
func TestAuthToken_NoCurrentContext(t *testing.T) {
cfg := &config.Config{}
store := secrets.NewMemStore()
iostreams.SetForTest(t)
err := runToken(tokenTestFactory(t, cfg, store), nil)
if err == nil {
t.Fatal("expected error, got nil")
}
if !cmdutil.IsAuthError(err) {
t.Errorf("want auth.* code, got %v", err)
}
}
func TestAuthToken_ContextOverride(t *testing.T) {
cfg := &config.Config{
CurrentContext: "prod",
Contexts: map[string]config.Context{
"prod": {Host: "https://prod.example.com", TokenRef: "prod:access"},
"staging": {Host: "https://staging.example.com", APIKeyRef: "staging:api_key"},
},
}
store := secrets.NewMemStore()
_ = store.Set("prod", "access", "prod-jwt")
_ = store.Set("staging", "api_key", "staging-key")
f := tokenTestFactory(t, cfg, store)
f.ContextOverride = "staging"
out, _ := iostreams.SetForTest(t)
if err := runToken(f, nil); err != nil {
t.Fatalf("runToken: %v", err)
}
if got := out.String(); got != "staging-key" {
t.Errorf("expected staging-key (override), got %q", got)
}
}
func TestAuthToken_NoStoredCredential(t *testing.T) {
cfg := &config.Config{
CurrentContext: "prod",
Contexts: map[string]config.Context{
"prod": {Host: "https://kb.example.com", TokenRef: "prod:access"},
},
}
store := secrets.NewMemStore()
// no Set — keyring is empty
iostreams.SetForTest(t)
err := runToken(tokenTestFactory(t, cfg, store), nil)
if err == nil {
t.Fatal("expected auth.unauthenticated, got nil")
}
if !cmdutil.IsAuthError(err) {
t.Errorf("want auth.*, got %v", err)
}
}
func TestAuthToken_ContextWithNoCredentialRefs(t *testing.T) {
cfg := &config.Config{
CurrentContext: "empty",
Contexts: map[string]config.Context{
"empty": {Host: "https://kb.example.com"}, // no TokenRef or APIKeyRef
},
}
store := secrets.NewMemStore()
iostreams.SetForTest(t)
err := runToken(tokenTestFactory(t, cfg, store), nil)
if err == nil {
t.Fatal("expected auth.unauthenticated, got nil")
}
if !cmdutil.IsAuthError(err) {
t.Errorf("want auth.*, got %v", err)
}
}