feat(cli): auth login + auth status commands (PR-4)
First two leaf commands and the auth/ command group, registered under the root command tree. auth login: - Email + password (interactive huh prompter) OR --with-token (read API key from stdin) for headless / CI use - Validates --host (required, must be http/https URL) - Persists access + refresh tokens (password mode) or api_key (token mode) into the secrets store wired in PR-3 — uses Store.Ref to record the URI scheme without leaking concrete backend type - Writes the named context to ~/.config/weknora/config.yaml and sets it as current_context - Typed loginResult payload for --json output (no map[string]any) auth status: - Calls client.GetCurrentUser -> /auth/me, prints context / host / user / tenant. --json emits a typed statusResult envelope with _meta.context and tenant_id populated for agents. - Service interface narrowed to just GetCurrentUser; tests inject fakes by overriding Factory.Client (no runF gymnastics). cmd/root.go: register \`auth\` parent under the root tree.
This commit is contained in:
@@ -0,0 +1,29 @@
|
||||
// Package auth holds the cobra commands for authentication
|
||||
// (login / status / logout / refresh). v0.0 ships login + status; logout
|
||||
// lands in v0.4 and refresh in v0.3.
|
||||
package auth
|
||||
|
||||
import (
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||
)
|
||||
|
||||
// NewCmdAuth builds the `weknora auth` command tree and registers its
|
||||
// subcommands. Called from cli/cmd/root.go.
|
||||
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() },
|
||||
}
|
||||
cmd.AddCommand(NewCmdLogin(f, nil))
|
||||
cmd.AddCommand(NewCmdStatus(f))
|
||||
return cmd
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"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"
|
||||
"github.com/Tencent/WeKnora/cli/internal/testutil"
|
||||
sdk "github.com/Tencent/WeKnora/client"
|
||||
)
|
||||
|
||||
func TestNewCmdAuth_TreeShape(t *testing.T) {
|
||||
cmd := NewCmdAuth(&cmdutil.Factory{})
|
||||
assert.Equal(t, "auth", cmd.Use)
|
||||
subs := map[string]*cobra.Command{}
|
||||
for _, c := range cmd.Commands() {
|
||||
subs[c.Use] = c
|
||||
}
|
||||
assert.Contains(t, subs, "login")
|
||||
assert.Contains(t, subs, "status")
|
||||
}
|
||||
|
||||
func TestNewCmdLogin_FlagsRegistered(t *testing.T) {
|
||||
cmd := NewCmdLogin(&cmdutil.Factory{}, nil)
|
||||
for _, name := range []string{"host", "context", "with-token", "json"} {
|
||||
assert.NotNilf(t, cmd.Flags().Lookup(name), "flag %s missing", name)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewCmdLogin_InvokesRunF(t *testing.T) {
|
||||
iostreams.SetForTest(t)
|
||||
called := false
|
||||
store := secrets.NewMemStore()
|
||||
f := &cmdutil.Factory{
|
||||
Secrets: func() (secrets.Store, error) { return store, nil },
|
||||
}
|
||||
cmd := NewCmdLogin(f, func(_ context.Context, opts *LoginOptions, _ *cmdutil.Factory, _ LoginService) error {
|
||||
called = true
|
||||
assert.Equal(t, "https://kb.example.com", opts.Host)
|
||||
assert.True(t, opts.WithToken)
|
||||
return nil
|
||||
})
|
||||
cmd.SetArgs([]string{"--host", "https://kb.example.com", "--with-token"})
|
||||
require.NoError(t, cmd.Execute())
|
||||
assert.True(t, called)
|
||||
}
|
||||
|
||||
func TestLoginServiceFor(t *testing.T) {
|
||||
assert.Nil(t, loginServiceFor(""))
|
||||
assert.NotNil(t, loginServiceFor("https://x"))
|
||||
}
|
||||
|
||||
func TestPersistAPIKey_WritesContext(t *testing.T) {
|
||||
iostreams.SetForTest(t)
|
||||
testutil.XDGTempDir(t)
|
||||
store := secrets.NewMemStore()
|
||||
f := &cmdutil.Factory{
|
||||
Config: func() (*config.Config, error) { return config.Load() },
|
||||
Prompter: func() prompt.Prompter { return prompt.AgentPrompter{} },
|
||||
Secrets: func() (secrets.Store, error) { return store, nil },
|
||||
}
|
||||
opts := &LoginOptions{
|
||||
Host: "https://kb.example.com",
|
||||
Context: "ci",
|
||||
APIKey: "sk-zzz",
|
||||
}
|
||||
require.NoError(t, persistAPIKey(opts, f))
|
||||
v, _ := store.Get("ci", "api_key")
|
||||
assert.Equal(t, "sk-zzz", v)
|
||||
cfg, _ := f.Config()
|
||||
assert.Equal(t, "ci", cfg.CurrentContext)
|
||||
assert.Equal(t, "https://kb.example.com", cfg.Contexts["ci"].Host)
|
||||
// APIKeyRef should be the mem:// URI from the store's Ref method.
|
||||
assert.Equal(t, "mem://ci/api_key", cfg.Contexts["ci"].APIKeyRef)
|
||||
}
|
||||
|
||||
func TestPersistJWT_StoresBothTokens(t *testing.T) {
|
||||
iostreams.SetForTest(t)
|
||||
testutil.XDGTempDir(t)
|
||||
store := secrets.NewMemStore()
|
||||
f := &cmdutil.Factory{
|
||||
Config: func() (*config.Config, error) { return config.Load() },
|
||||
Prompter: func() prompt.Prompter { return prompt.AgentPrompter{} },
|
||||
Secrets: func() (secrets.Store, error) { return store, nil },
|
||||
}
|
||||
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))
|
||||
a, _ := store.Get("p", "access")
|
||||
r, _ := store.Get("p", "refresh")
|
||||
assert.Equal(t, "jwt-acc", a)
|
||||
assert.Equal(t, "jwt-ref", r)
|
||||
}
|
||||
|
||||
func TestReadStdinTrimmed(t *testing.T) {
|
||||
out, err := readStdinTrimmed(strings.NewReader(" hello \n"))
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "hello", out)
|
||||
|
||||
out, err = readStdinTrimmed(nil)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "", out)
|
||||
}
|
||||
@@ -0,0 +1,239 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/url"
|
||||
"strings"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||
"github.com/Tencent/WeKnora/cli/internal/config"
|
||||
"github.com/Tencent/WeKnora/cli/internal/format"
|
||||
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
||||
sdk "github.com/Tencent/WeKnora/client"
|
||||
)
|
||||
|
||||
// LoginOptions is the configuration captured from flags + prompts.
|
||||
type LoginOptions struct {
|
||||
Host string // --host
|
||||
Context string // --context name to write
|
||||
WithToken bool // --with-token (read api key from stdin instead of prompting password)
|
||||
APIKey string // populated by --with-token from stdin
|
||||
Email string
|
||||
Password string
|
||||
JSONOut bool
|
||||
StdinReader io.Reader // override for tests
|
||||
}
|
||||
|
||||
// LoginService is the narrow SDK surface auth login depends on.
|
||||
// *sdk.Client satisfies it implicitly via the new Login(ctx, LoginRequest)
|
||||
// signature added in client/auth.go.
|
||||
type LoginService interface {
|
||||
Login(ctx context.Context, req sdk.LoginRequest) (*sdk.LoginResponse, error)
|
||||
}
|
||||
|
||||
// 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 {
|
||||
opts := &LoginOptions{}
|
||||
cmd := &cobra.Command{
|
||||
Use: "login",
|
||||
Short: "Authenticate against a WeKnora server and persist credentials",
|
||||
Long: `Log in by email + password (interactive prompt) or pipe an API key with --with-token.
|
||||
|
||||
Credentials are persisted to the OS keyring when available; otherwise to a
|
||||
0600 file under $XDG_CONFIG_HOME/weknora/secrets. The named context becomes
|
||||
the current_context in ~/.config/weknora/config.yaml.`,
|
||||
RunE: func(c *cobra.Command, args []string) error {
|
||||
run := runF
|
||||
if run == nil {
|
||||
run = runLogin
|
||||
}
|
||||
svc := loginServiceFor(opts.Host)
|
||||
if opts.StdinReader == nil {
|
||||
opts.StdinReader = iostreams.IO.In
|
||||
}
|
||||
return run(c.Context(), opts, f, svc)
|
||||
},
|
||||
}
|
||||
cmd.Flags().StringVar(&opts.Host, "host", "", "WeKnora server URL, e.g. https://kb.example.com")
|
||||
cmd.Flags().StringVar(&opts.Context, "context", "default", "Name to assign this context 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.MustRequireFlag(cmd, "host")
|
||||
return cmd
|
||||
}
|
||||
|
||||
// loginServiceFor returns a fresh SDK client targeting host. login.go cannot
|
||||
// reuse Factory.Client because that closure requires an existing context.
|
||||
func loginServiceFor(host string) LoginService {
|
||||
if host == "" {
|
||||
return nil
|
||||
}
|
||||
return sdk.NewClient(host)
|
||||
}
|
||||
|
||||
func runLogin(ctx context.Context, opts *LoginOptions, f *cmdutil.Factory, svc LoginService) error {
|
||||
if err := validateHost(opts.Host); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if opts.WithToken {
|
||||
key, err := readStdinTrimmed(opts.StdinReader)
|
||||
if err != nil {
|
||||
return cmdutil.Wrapf(cmdutil.CodeLocalFileIO, err, "read stdin")
|
||||
}
|
||||
if key == "" {
|
||||
return cmdutil.NewError(cmdutil.CodeInputMissingFlag, "--with-token requires an API key piped to stdin")
|
||||
}
|
||||
opts.APIKey = key
|
||||
return persistAPIKey(opts, f)
|
||||
}
|
||||
|
||||
// Interactive: prompt for email + password.
|
||||
if svc == nil {
|
||||
return cmdutil.NewError(cmdutil.CodeServerError, "login: no SDK client (host missing?)")
|
||||
}
|
||||
if opts.Email == "" || opts.Password == "" {
|
||||
p := f.Prompter()
|
||||
if opts.Email == "" {
|
||||
email, err := p.Input("Email", "")
|
||||
if err != nil {
|
||||
return cmdutil.Wrapf(cmdutil.CodeInputMissingFlag, err, "email prompt")
|
||||
}
|
||||
opts.Email = email
|
||||
}
|
||||
if opts.Password == "" {
|
||||
pw, err := p.Password("Password")
|
||||
if err != nil {
|
||||
return cmdutil.Wrapf(cmdutil.CodeInputMissingFlag, err, "password prompt")
|
||||
}
|
||||
opts.Password = pw
|
||||
}
|
||||
}
|
||||
|
||||
resp, err := svc.Login(ctx, sdk.LoginRequest{Email: opts.Email, Password: opts.Password})
|
||||
if err != nil {
|
||||
return cmdutil.Wrapf(cmdutil.CodeAuthBadCredential, err, "login")
|
||||
}
|
||||
if !resp.Success || resp.Token == "" {
|
||||
return cmdutil.NewError(cmdutil.CodeAuthBadCredential, fmt.Sprintf("login refused: %s", resp.Message))
|
||||
}
|
||||
|
||||
return persistJWT(opts, f, resp)
|
||||
}
|
||||
|
||||
// persistAPIKey saves the --with-token API key and writes the context.
|
||||
func persistAPIKey(opts *LoginOptions, f *cmdutil.Factory) error {
|
||||
store, err := f.Secrets()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
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{
|
||||
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 {
|
||||
store, err := f.Secrets()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := store.Set(opts.Context, "access", resp.Token); err != nil {
|
||||
return cmdutil.Wrapf(cmdutil.CodeLocalKeychainDenied, err, "save access token")
|
||||
}
|
||||
if resp.RefreshToken != "" {
|
||||
if err := store.Set(opts.Context, "refresh", resp.RefreshToken); err != nil {
|
||||
return cmdutil.Wrapf(cmdutil.CodeLocalKeychainDenied, err, "save refresh token")
|
||||
}
|
||||
}
|
||||
c := &config.Context{
|
||||
Host: opts.Host,
|
||||
TokenRef: store.Ref(opts.Context, "access"),
|
||||
RefreshRef: store.Ref(opts.Context, "refresh"),
|
||||
}
|
||||
if resp.User != nil {
|
||||
c.User = resp.User.Email
|
||||
c.TenantID = resp.User.TenantID
|
||||
}
|
||||
return saveContextRef(opts, f, c, resp.User)
|
||||
}
|
||||
|
||||
// loginResult is the typed payload emitted by `--json`. mode is derived from
|
||||
// whether the server returned a user (password flow) vs API-key flow.
|
||||
type loginResult struct {
|
||||
Context string `json:"context"`
|
||||
Host string `json:"host"`
|
||||
Mode string `json:"mode"` // "password" or "api-key"
|
||||
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 {
|
||||
cfg, err := f.Config()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if cfg.Contexts == nil {
|
||||
cfg.Contexts = map[string]config.Context{}
|
||||
}
|
||||
cfg.Contexts[opts.Context] = *ctx
|
||||
cfg.CurrentContext = opts.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 user != nil {
|
||||
result.Mode = "password"
|
||||
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,
|
||||
}))
|
||||
}
|
||||
who := opts.Context
|
||||
if user != nil {
|
||||
who = user.Email
|
||||
}
|
||||
fmt.Fprintf(iostreams.IO.Out, "✓ Logged in to %s as %s (context=%s)\n", opts.Host, who, opts.Context)
|
||||
return nil
|
||||
}
|
||||
|
||||
// validateHost rejects empty / non-http URLs early so we surface a clean
|
||||
// flag error instead of failing inside the SDK transport.
|
||||
func validateHost(host string) error {
|
||||
if host == "" {
|
||||
return cmdutil.NewError(cmdutil.CodeInputMissingFlag, "--host is required")
|
||||
}
|
||||
u, err := url.Parse(host)
|
||||
if err != nil || (u.Scheme != "http" && u.Scheme != "https") {
|
||||
return cmdutil.NewError(cmdutil.CodeInputInvalidArgument, fmt.Sprintf("--host must be http(s) URL, got %q", host))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// readStdinTrimmed reads all of r and returns the result with surrounding
|
||||
// whitespace stripped. Empty result is returned as-is for the caller to
|
||||
// validate.
|
||||
func readStdinTrimmed(r io.Reader) (string, error) {
|
||||
if r == nil {
|
||||
return "", nil
|
||||
}
|
||||
b, err := io.ReadAll(r)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return strings.TrimSpace(string(b)), nil
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"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"
|
||||
"github.com/Tencent/WeKnora/cli/internal/testutil"
|
||||
sdk "github.com/Tencent/WeKnora/client"
|
||||
)
|
||||
|
||||
// fakeLoginService captures the email/password it received.
|
||||
type fakeLoginService struct {
|
||||
resp *sdk.LoginResponse
|
||||
err error
|
||||
got struct{ email, password string }
|
||||
}
|
||||
|
||||
func (f *fakeLoginService) Login(_ context.Context, req sdk.LoginRequest) (*sdk.LoginResponse, error) {
|
||||
f.got.email = req.Email
|
||||
f.got.password = req.Password
|
||||
return f.resp, f.err
|
||||
}
|
||||
|
||||
// scriptedPrompter satisfies prompt.Prompter with predetermined values.
|
||||
type scriptedPrompter struct{ email, password string }
|
||||
|
||||
func (s scriptedPrompter) Input(string, string) (string, error) { return s.email, nil }
|
||||
func (s scriptedPrompter) Password(string) (string, error) { return s.password, nil }
|
||||
func (s scriptedPrompter) Confirm(string, bool) (bool, error) { return true, nil }
|
||||
|
||||
func newTestFactoryWithConfig(t *testing.T, p prompt.Prompter) (*cmdutil.Factory, *secrets.MemStore) {
|
||||
t.Helper()
|
||||
testutil.XDGTempDir(t)
|
||||
store := secrets.NewMemStore()
|
||||
return &cmdutil.Factory{
|
||||
Config: func() (*config.Config, error) { return config.Load() },
|
||||
Client: func() (*sdk.Client, error) { panic("client") },
|
||||
Prompter: func() prompt.Prompter { return p },
|
||||
Secrets: func() (secrets.Store, error) { return store, nil },
|
||||
}, store
|
||||
}
|
||||
|
||||
func TestRunLogin_PasswordMode(t *testing.T) {
|
||||
iostreams.SetForTest(t)
|
||||
f, store := newTestFactoryWithConfig(t, scriptedPrompter{email: "a@b.c", password: "secret"})
|
||||
svc := &fakeLoginService{resp: &sdk.LoginResponse{
|
||||
Success: true,
|
||||
Token: "jwt-access",
|
||||
User: &sdk.AuthUser{ID: "u1", Email: "a@b.c", TenantID: 7},
|
||||
}}
|
||||
opts := &LoginOptions{
|
||||
Host: "https://kb.example.com",
|
||||
Context: "prod",
|
||||
}
|
||||
require.NoError(t, runLogin(context.Background(), opts, f, svc))
|
||||
|
||||
assert.Equal(t, "a@b.c", svc.got.email)
|
||||
assert.Equal(t, "secret", svc.got.password)
|
||||
|
||||
got, _ := store.Get("prod", "access")
|
||||
assert.Equal(t, "jwt-access", got)
|
||||
}
|
||||
|
||||
func TestRunLogin_WithToken(t *testing.T) {
|
||||
iostreams.SetForTest(t)
|
||||
f, store := newTestFactoryWithConfig(t, prompt.AgentPrompter{})
|
||||
opts := &LoginOptions{
|
||||
Host: "https://kb.example.com",
|
||||
Context: "ci",
|
||||
WithToken: true,
|
||||
StdinReader: strings.NewReader(" sk-1234 \n"),
|
||||
}
|
||||
require.NoError(t, runLogin(context.Background(), opts, f, nil))
|
||||
got, _ := store.Get("ci", "api_key")
|
||||
assert.Equal(t, "sk-1234", got)
|
||||
}
|
||||
|
||||
func TestRunLogin_WithToken_Empty(t *testing.T) {
|
||||
iostreams.SetForTest(t)
|
||||
f, _ := newTestFactoryWithConfig(t, prompt.AgentPrompter{})
|
||||
opts := &LoginOptions{
|
||||
Host: "https://kb.example.com",
|
||||
Context: "ci",
|
||||
WithToken: true,
|
||||
StdinReader: strings.NewReader(""),
|
||||
}
|
||||
err := runLogin(context.Background(), opts, f, nil)
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "input.missing_flag")
|
||||
}
|
||||
|
||||
func TestRunLogin_BadHost(t *testing.T) {
|
||||
iostreams.SetForTest(t)
|
||||
f, _ := newTestFactoryWithConfig(t, prompt.AgentPrompter{})
|
||||
err := runLogin(context.Background(), &LoginOptions{Host: "ftp://nope"}, f, nil)
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "input.invalid_argument")
|
||||
}
|
||||
|
||||
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)
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "auth.bad_credential")
|
||||
}
|
||||
|
||||
func TestValidateHost(t *testing.T) {
|
||||
require.NoError(t, validateHost("https://kb.example.com"))
|
||||
require.NoError(t, validateHost("http://localhost:8080"))
|
||||
require.Error(t, validateHost(""))
|
||||
require.Error(t, validateHost("ftp://x"))
|
||||
require.Error(t, validateHost("not a url"))
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||
"github.com/Tencent/WeKnora/cli/internal/format"
|
||||
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
||||
sdk "github.com/Tencent/WeKnora/client"
|
||||
)
|
||||
|
||||
// StatusOptions captures the (sparse) configuration of `weknora auth status`.
|
||||
type StatusOptions struct {
|
||||
JSONOut bool
|
||||
}
|
||||
|
||||
// StatusService is the narrow SDK surface auth status depends on.
|
||||
type StatusService interface {
|
||||
GetCurrentUser(ctx context.Context) (*sdk.CurrentUserResponse, error)
|
||||
}
|
||||
|
||||
// statusResult is the typed payload emitted by `--json`.
|
||||
type statusResult struct {
|
||||
Context string `json:"context"`
|
||||
UserID string `json:"user_id,omitempty"`
|
||||
Email string `json:"email,omitempty"`
|
||||
TenantID uint64 `json:"tenant_id,omitempty"`
|
||||
TenantName string `json:"tenant_name,omitempty"`
|
||||
}
|
||||
|
||||
// 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",
|
||||
RunE: func(c *cobra.Command, args []string) error {
|
||||
cli, err := f.Client()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return runStatus(c.Context(), opts, f, cli)
|
||||
},
|
||||
}
|
||||
cmd.Flags().BoolVar(&opts.JSONOut, "json", false, "Output JSON envelope")
|
||||
return cmd
|
||||
}
|
||||
|
||||
func runStatus(ctx context.Context, opts *StatusOptions, f *cmdutil.Factory, svc StatusService) error {
|
||||
if svc == nil {
|
||||
return cmdutil.NewError(cmdutil.CodeAuthUnauthenticated, "no SDK client available; run `weknora auth login`")
|
||||
}
|
||||
resp, err := svc.GetCurrentUser(ctx)
|
||||
if err != nil {
|
||||
return cmdutil.Wrapf(cmdutil.ClassifyHTTPError(err), err, "fetch current user")
|
||||
}
|
||||
user := resp.Data.User
|
||||
tenant := resp.Data.Tenant
|
||||
|
||||
cfg, err := f.Config()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if opts.JSONOut {
|
||||
var tenantID uint64
|
||||
result := statusResult{Context: cfg.CurrentContext}
|
||||
if user != nil {
|
||||
result.UserID = user.ID
|
||||
result.Email = user.Email
|
||||
result.TenantID = user.TenantID
|
||||
tenantID = user.TenantID
|
||||
}
|
||||
if tenant != nil {
|
||||
result.TenantName = tenant.Name
|
||||
}
|
||||
return cmdutil.NewJSONExporter().Write(iostreams.IO.Out, format.Success(result, &format.Meta{
|
||||
Context: cfg.CurrentContext,
|
||||
TenantID: tenantID,
|
||||
}))
|
||||
}
|
||||
|
||||
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, "host: %s\n", host)
|
||||
if user != nil {
|
||||
fmt.Fprintf(iostreams.IO.Out, "user: %s (%s)\n", user.Email, user.ID)
|
||||
fmt.Fprintf(iostreams.IO.Out, "tenant: %d", user.TenantID)
|
||||
if tenant != nil {
|
||||
fmt.Fprintf(iostreams.IO.Out, " (%s)", tenant.Name)
|
||||
}
|
||||
fmt.Fprintln(iostreams.IO.Out)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"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/testutil"
|
||||
sdk "github.com/Tencent/WeKnora/client"
|
||||
)
|
||||
|
||||
type fakeStatusService struct {
|
||||
resp *sdk.CurrentUserResponse
|
||||
err error
|
||||
}
|
||||
|
||||
func (f *fakeStatusService) GetCurrentUser(_ context.Context) (*sdk.CurrentUserResponse, error) {
|
||||
return f.resp, f.err
|
||||
}
|
||||
|
||||
func newCurrentUserResponse(user *sdk.AuthUser, tenant *sdk.AuthTenant) *sdk.CurrentUserResponse {
|
||||
r := &sdk.CurrentUserResponse{Success: true}
|
||||
r.Data.User = user
|
||||
r.Data.Tenant = tenant
|
||||
return r
|
||||
}
|
||||
|
||||
func TestRunStatus_HumanOutput(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
testutil.XDGTempDir(t)
|
||||
require.NoError(t, config.Save(&config.Config{
|
||||
CurrentContext: "prod",
|
||||
Contexts: map[string]config.Context{
|
||||
"prod": {Host: "https://kb.example.com", TenantID: 7},
|
||||
},
|
||||
}))
|
||||
f := &cmdutil.Factory{
|
||||
Config: func() (*config.Config, error) { return config.Load() },
|
||||
Prompter: func() prompt.Prompter { return prompt.AgentPrompter{} },
|
||||
}
|
||||
svc := &fakeStatusService{
|
||||
resp: newCurrentUserResponse(
|
||||
&sdk.AuthUser{ID: "u1", Email: "alice@example.com", TenantID: 7},
|
||||
&sdk.AuthTenant{ID: 7, Name: "Acme"},
|
||||
),
|
||||
}
|
||||
require.NoError(t, runStatus(context.Background(), &StatusOptions{}, f, svc))
|
||||
got := out.String()
|
||||
assert.Contains(t, got, "context: prod")
|
||||
assert.Contains(t, got, "host: https://kb.example.com")
|
||||
assert.Contains(t, got, "alice@example.com")
|
||||
assert.Contains(t, got, "Acme")
|
||||
}
|
||||
|
||||
func TestRunStatus_JSONOutput(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
testutil.XDGTempDir(t)
|
||||
require.NoError(t, config.Save(&config.Config{
|
||||
CurrentContext: "prod",
|
||||
Contexts: map[string]config.Context{"prod": {Host: "https://x"}},
|
||||
}))
|
||||
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))
|
||||
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)
|
||||
require.Error(t, err)
|
||||
assert.True(t, cmdutil.IsAuthError(err))
|
||||
}
|
||||
|
||||
func TestRunStatus_SDKError_Transport(t *testing.T) {
|
||||
iostreams.SetForTest(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})
|
||||
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.
|
||||
assert.True(t, cmdutil.IsTransient(err), "expected transient/network classification, got %v", err)
|
||||
}
|
||||
|
||||
func TestRunStatus_SDKError_HTTP401(t *testing.T) {
|
||||
iostreams.SetForTest(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")})
|
||||
require.Error(t, err)
|
||||
assert.True(t, cmdutil.IsAuthError(err))
|
||||
}
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/cmd/auth"
|
||||
"github.com/Tencent/WeKnora/cli/internal/agent"
|
||||
"github.com/Tencent/WeKnora/cli/internal/build"
|
||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||
@@ -144,6 +145,7 @@ func newRootCmd(f *cmdutil.Factory) *cobra.Command {
|
||||
})
|
||||
|
||||
cmd.AddCommand(newVersionCmd(f))
|
||||
cmd.AddCommand(auth.NewCmdAuth(f))
|
||||
return cmd
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user