refactor(cli,auth): consolidate auth/profile model (BREAKING)
Auth now acts on the active profile instead of per-command --host/--name:
register a target with `profile add <name> --host <url> --use`, then
`auth login`. `auth login --with-token` reads an API key from stdin
(non-interactive, agent default); password login is interactive-only.
`auth token` prints the raw credential by default (clean $(...) capture);
--format json emits the {token,mode,profile} envelope, --jq implies json.
Login mode label corrected (api-key vs bearer). profile use and the auth/
profile read commands gain --dry-run / agent-help where they were missing.
This commit is contained in:
@@ -32,12 +32,14 @@ func TestNewCmdAuth_TreeShape(t *testing.T) {
|
||||
func TestNewCmdLogin_FlagsRegistered(t *testing.T) {
|
||||
cmd := NewCmdLogin(&cmdutil.Factory{}, nil)
|
||||
// --format is a persistent root flag (v0.7); only per-command flags here.
|
||||
for _, name := range []string{"host", "name", "with-token"} {
|
||||
assert.NotNilf(t, cmd.Flags().Lookup(name), "flag %s missing", name)
|
||||
}
|
||||
assert.NotNil(t, cmd.Flags().Lookup("with-token"), "flag with-token missing")
|
||||
// login authenticates the active profile; host/name come from config
|
||||
// (created via `profile add`), so these flags are gone.
|
||||
assert.Nil(t, cmd.Flags().Lookup("host"), "auth login must not declare --host (v0.9)")
|
||||
assert.Nil(t, cmd.Flags().Lookup("name"), "auth login must not declare --name (v0.9)")
|
||||
// --profile is the global persistent override; local registration would
|
||||
// silently shadow it.
|
||||
assert.Nil(t, cmd.Flags().Lookup("profile"), "auth login must not declare a local --profile flag (use --name)")
|
||||
assert.Nil(t, cmd.Flags().Lookup("profile"), "auth login must not declare a local --profile flag (use the global --profile)")
|
||||
}
|
||||
|
||||
func TestNewCmdLogin_InvokesRunF(t *testing.T) {
|
||||
@@ -49,11 +51,12 @@ func TestNewCmdLogin_InvokesRunF(t *testing.T) {
|
||||
}
|
||||
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)
|
||||
// host/profile resolve inside runLogin from the active profile;
|
||||
// the runF seam just receives the parsed flags.
|
||||
assert.True(t, opts.WithToken)
|
||||
return nil
|
||||
})
|
||||
cmd.SetArgs([]string{"--host", "https://kb.example.com", "--with-token"})
|
||||
cmd.SetArgs([]string{"--with-token"})
|
||||
require.NoError(t, cmd.Execute())
|
||||
assert.True(t, called)
|
||||
}
|
||||
@@ -72,6 +75,12 @@ func TestPersistAPIKey_WritesContext(t *testing.T) {
|
||||
Prompter: func() prompt.Prompter { return prompt.AgentPrompter{} },
|
||||
Secrets: func() (secrets.Store, error) { return store, nil },
|
||||
}
|
||||
// persistAPIKey MERGES into the existing active profile record (created
|
||||
// via `profile add`) rather than creating it; seed it first.
|
||||
require.NoError(t, config.Save(&config.Config{
|
||||
CurrentProfile: "ci",
|
||||
Profiles: map[string]config.Profile{"ci": {Host: "https://kb.example.com"}},
|
||||
}))
|
||||
opts := &LoginOptions{
|
||||
Host: "https://kb.example.com",
|
||||
Profile: "ci",
|
||||
@@ -81,8 +90,8 @@ func TestPersistAPIKey_WritesContext(t *testing.T) {
|
||||
v, _ := store.Get("ci", "api_key")
|
||||
assert.Equal(t, "sk-zzz", v)
|
||||
cfg, _ := f.Config()
|
||||
assert.Equal(t, "ci", cfg.CurrentProfile)
|
||||
assert.Equal(t, "https://kb.example.com", cfg.Profiles["ci"].Host)
|
||||
assert.Equal(t, "ci", cfg.CurrentProfile, "active profile unchanged by login")
|
||||
assert.Equal(t, "https://kb.example.com", cfg.Profiles["ci"].Host, "existing host preserved by merge")
|
||||
// APIKeyRef should be the mem:// URI from the store's Ref method.
|
||||
assert.Equal(t, "mem://ci/api_key", cfg.Profiles["ci"].APIKeyRef)
|
||||
}
|
||||
|
||||
@@ -71,19 +71,19 @@ func TestAuthLogout_DryRun_RejectsNoProfiles(t *testing.T) {
|
||||
assert.Equal(t, cmdutil.CodeAuthUnauthenticated, typed.Code)
|
||||
}
|
||||
|
||||
// TestAuthLogout_DryRun_RejectsUnknownName: --name on a profile that doesn't
|
||||
// exist → live path returns local.profile_not_found; --dry-run must do the
|
||||
// same.
|
||||
func TestAuthLogout_DryRun_RejectsUnknownName(t *testing.T) {
|
||||
// TestAuthLogout_DryRun_RejectsMissingActiveProfile: the active profile name
|
||||
// (e.g. set via the global --profile) has no config entry → live path returns
|
||||
// local.profile_not_found; --dry-run must do the same.
|
||||
func TestAuthLogout_DryRun_RejectsMissingActiveProfile(t *testing.T) {
|
||||
iostreams.SetForTest(t)
|
||||
cfg := &config.Config{
|
||||
CurrentProfile: "prod",
|
||||
CurrentProfile: "ghost", // active profile with no matching entry
|
||||
Profiles: map[string]config.Profile{"prod": {Host: "https://prod"}},
|
||||
}
|
||||
root := withRootHarnessAuth(NewCmdLogout(authDryRunFactory(t, cfg)),
|
||||
"--name", "ghost", "--dry-run", "--format", "json")
|
||||
"--dry-run", "--format", "json")
|
||||
err := root.Execute()
|
||||
require.Error(t, err, "dry-run must reject unknown --name")
|
||||
require.Error(t, err, "dry-run must reject a missing active profile")
|
||||
var typed *cmdutil.Error
|
||||
require.True(t, errors.As(err, &typed), "expected *cmdutil.Error, got %T %v", err, err)
|
||||
assert.Equal(t, cmdutil.CodeLocalProfileNotFound, typed.Code)
|
||||
|
||||
@@ -48,6 +48,11 @@ func NewCmdList(f *cmdutil.Factory) *cobra.Command {
|
||||
},
|
||||
}
|
||||
cmdutil.AddFormatFlag(cmd, authListFields...)
|
||||
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
|
||||
UsedFor: "list configured profiles and their credential mode (bearer / api-key)",
|
||||
Examples: []string{"weknora auth list", "weknora auth list --jq '.data[].name'"},
|
||||
Output: "envelope.data is an array of profiles with name, host, mode, and which is active",
|
||||
})
|
||||
return cmd
|
||||
}
|
||||
|
||||
|
||||
+122
-42
@@ -23,10 +23,13 @@ var authLoginFields = []string{
|
||||
"profile", "host", "mode", "user", "tenant_id",
|
||||
}
|
||||
|
||||
// LoginOptions is the configuration captured from flags + prompts.
|
||||
// LoginOptions is the configuration captured from flags + prompts. Host and
|
||||
// Profile are resolved from the active profile in config (not from flags) -
|
||||
// `auth login` authenticates the already-existing active profile, created
|
||||
// beforehand with `weknora profile add <name> --host <h> --use`.
|
||||
type LoginOptions struct {
|
||||
Host string // --host
|
||||
Profile string // --name: profile name to write into config.yaml
|
||||
Host string // resolved from the active profile's Host in config
|
||||
Profile string // resolved active profile name (honors global --profile)
|
||||
WithToken bool // --with-token: read api key from stdin instead of prompting password
|
||||
APIKey string // populated by --with-token from stdin
|
||||
Email string
|
||||
@@ -68,12 +71,16 @@ func NewCmdLogin(f *cmdutil.Factory, runF func(context.Context, *LoginOptions, *
|
||||
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.
|
||||
Short: "Authenticate the active profile against its WeKnora server",
|
||||
Long: `Authenticate the active profile by email + password (interactive prompt) or
|
||||
pipe an API key with --with-token.
|
||||
|
||||
` + "`auth login`" + ` operates on the active profile (override with the global
|
||||
--profile flag). Create the profile first with
|
||||
` + "`weknora profile add <name> --host <h> --use`" + `, then run ` + "`weknora auth login`" + `.
|
||||
|
||||
Credentials are persisted to the OS keyring when available; otherwise to a
|
||||
0600 file under $XDG_CONFIG_HOME/weknora/secrets. The named profile becomes
|
||||
the current_profile in ~/.config/weknora/config.yaml.`,
|
||||
0600 file under $XDG_CONFIG_HOME/weknora/secrets.`,
|
||||
Args: cobra.NoArgs,
|
||||
RunE: func(c *cobra.Command, args []string) error {
|
||||
fopts, err := cmdutil.CheckFormatFlag(c)
|
||||
@@ -81,25 +88,61 @@ the current_profile in ~/.config/weknora/config.yaml.`,
|
||||
return err
|
||||
}
|
||||
fopts.ResolveDefault(iostreams.IO.IsStdoutTTY())
|
||||
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, fopts, f, svc)
|
||||
if runF != nil {
|
||||
// Test seam: the injected runF supplies its own service and
|
||||
// (where needed) seeds opts.Host / opts.Profile itself.
|
||||
return runF(c.Context(), opts, fopts, f, nil)
|
||||
}
|
||||
return runLogin(c.Context(), opts, fopts, f, nil)
|
||||
},
|
||||
}
|
||||
cmd.Flags().StringVar(&opts.Host, "host", "", "WeKnora server URL, e.g. https://kb.example.com")
|
||||
cmd.Flags().StringVar(&opts.Profile, "name", "default", "Profile name to register in config.yaml")
|
||||
cmd.Flags().BoolVar(&opts.WithToken, "with-token", false, "Read an API key from stdin instead of prompting for password")
|
||||
cmdutil.AddFormatFlag(cmd, authLoginFields...)
|
||||
_ = cmd.MarkFlagRequired("host")
|
||||
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
|
||||
UsedFor: "authenticate the active profile; --with-token reads an API key from stdin (non-interactive)",
|
||||
Examples: []string{`echo "$WEKNORA_API_KEY" | weknora auth login --with-token`},
|
||||
Output: "envelope.data is {profile, host, mode, user, tenant_id} on success",
|
||||
Warnings: []string{
|
||||
"a profile must exist and be active first (`weknora profile add <n> --host <url> --use`)",
|
||||
"password login is interactive-only (no flags) — agents must use --with-token with the key piped to stdin",
|
||||
},
|
||||
})
|
||||
return cmd
|
||||
}
|
||||
|
||||
// resolveActiveProfile loads config and resolves the active profile (honoring
|
||||
// the global --profile override) plus its persisted Host. `auth login`
|
||||
// authenticates an already-existing profile; profile creation is `profile
|
||||
// add`'s job. Returns typed errors when no active profile is configured or
|
||||
// the profile lacks a host.
|
||||
func resolveActiveProfile(f *cmdutil.Factory) (name, host string, err error) {
|
||||
// f.Config() already folds the global --profile / WEKNORA_PROFILE override
|
||||
// into cfg.CurrentProfile (same source f.ActiveProfile reads), so one load
|
||||
// resolves the active profile — matches logout/refresh.
|
||||
cfg, err := f.Config()
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
active := cfg.CurrentProfile
|
||||
if active == "" {
|
||||
return "", "", cmdutil.NewError(cmdutil.CodeAuthUnauthenticated,
|
||||
"no active profile; run `weknora profile add <name> --host <h> --use` first")
|
||||
}
|
||||
prof, ok := cfg.Profiles[active]
|
||||
if !ok {
|
||||
return "", "", cmdutil.NewError(cmdutil.CodeLocalProfileNotFound,
|
||||
fmt.Sprintf("active profile %q not found in config", active))
|
||||
}
|
||||
if prof.Host == "" {
|
||||
return "", "", cmdutil.NewError(cmdutil.CodeLocalConfigCorrupt,
|
||||
fmt.Sprintf("profile %q has no host", active))
|
||||
}
|
||||
return active, prof.Host, nil
|
||||
}
|
||||
|
||||
// loginServiceFor returns a fresh SDK client targeting host. login.go cannot
|
||||
// reuse Factory.Client because that closure requires an existing profile.
|
||||
func loginServiceFor(host string) LoginService {
|
||||
@@ -110,6 +153,19 @@ func loginServiceFor(host string) LoginService {
|
||||
}
|
||||
|
||||
func runLogin(ctx context.Context, opts *LoginOptions, fopts *cmdutil.FormatOptions, f *cmdutil.Factory, svc LoginService) error {
|
||||
// Resolve the target profile + host from the active profile in config.
|
||||
// `auth login` no longer takes --host / --name; it authenticates the
|
||||
// already-existing active profile (override via the global --profile).
|
||||
name, host, err := resolveActiveProfile(f)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
opts.Profile = name
|
||||
opts.Host = host
|
||||
if svc == nil {
|
||||
svc = loginServiceFor(host)
|
||||
}
|
||||
|
||||
if err := validateHost(opts.Host); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -146,10 +202,9 @@ func runLogin(ctx context.Context, opts *LoginOptions, fopts *cmdutil.FormatOpti
|
||||
return persistAPIKey(opts, fopts, f, user)
|
||||
}
|
||||
|
||||
// Interactive: prompt for email + password.
|
||||
if svc == nil {
|
||||
return cmdutil.NewError(cmdutil.CodeServerError, "login: no SDK client (host missing?)")
|
||||
}
|
||||
// Interactive: prompt for email + password. svc is always set by now
|
||||
// (loginServiceFor returns non-nil because resolveActiveProfile guarantees
|
||||
// a non-empty host).
|
||||
if opts.Email == "" || opts.Password == "" {
|
||||
p := f.Prompter()
|
||||
if opts.Email == "" {
|
||||
@@ -198,15 +253,17 @@ func persistAPIKey(opts *LoginOptions, fopts *cmdutil.FormatOptions, f *cmdutil.
|
||||
if err := store.Set(opts.Profile, "api_key", opts.APIKey); err != nil {
|
||||
return cmdutil.Wrapf(cmdutil.CodeLocalKeychainDenied, err, "save api key")
|
||||
}
|
||||
prof := &config.Profile{
|
||||
Host: opts.Host,
|
||||
APIKeyRef: store.Ref(opts.Profile, "api_key"),
|
||||
// Switching credential mode: this profile is now an API-key profile, so
|
||||
// any leftover JWT refs (from a prior password login) are stale. Set the
|
||||
// api-key ref and clear the token/refresh refs; keep Host + existing
|
||||
// User/TenantID (merged in saveProfileRef via applyUser).
|
||||
mutate := func(prof *config.Profile) {
|
||||
prof.APIKeyRef = store.Ref(opts.Profile, "api_key")
|
||||
prof.TokenRef = ""
|
||||
prof.RefreshRef = ""
|
||||
applyUser(prof, user)
|
||||
}
|
||||
if user != nil {
|
||||
prof.User = user.Email
|
||||
prof.TenantID = user.TenantID
|
||||
}
|
||||
return saveProfileRef(opts, fopts, f, prof, user)
|
||||
return saveProfileRef(opts, fopts, f, mutate, ModeAPIKey, user)
|
||||
}
|
||||
|
||||
// persistJWT saves access + refresh tokens and writes the profile.
|
||||
@@ -224,16 +281,30 @@ func persistJWT(opts *LoginOptions, fopts *cmdutil.FormatOptions, f *cmdutil.Fac
|
||||
return cmdutil.Wrapf(cmdutil.CodeLocalKeychainDenied, err, "save refresh token")
|
||||
}
|
||||
}
|
||||
prof := &config.Profile{
|
||||
Host: opts.Host,
|
||||
TokenRef: store.Ref(opts.Profile, "access"),
|
||||
RefreshRef: store.Ref(opts.Profile, "refresh"),
|
||||
// Switching to a JWT profile: set token refs and drop any stale api-key
|
||||
// ref; keep Host + existing User/TenantID (merged in saveProfileRef via applyUser).
|
||||
mutate := func(prof *config.Profile) {
|
||||
prof.TokenRef = store.Ref(opts.Profile, "access")
|
||||
prof.RefreshRef = store.Ref(opts.Profile, "refresh")
|
||||
prof.APIKeyRef = ""
|
||||
applyUser(prof, resp.User)
|
||||
}
|
||||
if resp.User != nil {
|
||||
prof.User = resp.User.Email
|
||||
prof.TenantID = resp.User.TenantID
|
||||
return saveProfileRef(opts, fopts, f, mutate, ModeBearer, resp.User)
|
||||
}
|
||||
|
||||
// applyUser overwrites prof.User / prof.TenantID only when the server actually
|
||||
// returned them. A nil user (or empty email) must NOT wipe an existing User
|
||||
// that was set during `profile add` or a prior login.
|
||||
func applyUser(prof *config.Profile, user *sdk.AuthUser) {
|
||||
if user == nil {
|
||||
return
|
||||
}
|
||||
if user.Email != "" {
|
||||
prof.User = user.Email
|
||||
}
|
||||
if user.TenantID != 0 {
|
||||
prof.TenantID = user.TenantID
|
||||
}
|
||||
return saveProfileRef(opts, fopts, f, prof, resp.User)
|
||||
}
|
||||
|
||||
// loginResult is the typed payload emitted by `--format json`. mode is derived from
|
||||
@@ -246,8 +317,13 @@ type loginResult struct {
|
||||
TenantID uint64 `json:"tenant_id,omitempty"`
|
||||
}
|
||||
|
||||
// saveProfileRef writes the profile to config.yaml and prints success.
|
||||
func saveProfileRef(opts *LoginOptions, fopts *cmdutil.FormatOptions, f *cmdutil.Factory, prof *config.Profile, user *sdk.AuthUser) error {
|
||||
// saveProfileRef MERGES the new credential refs into the EXISTING profile
|
||||
// record and prints success. The active profile already exists (created via
|
||||
// `profile add`, carrying Host and possibly User/TenantID); mutate sets only
|
||||
// the credential refs + any server-returned user, so re-login never clobbers
|
||||
// the host or wipes an existing user. cfg.CurrentProfile is left untouched -
|
||||
// `auth login` authenticates the already-active profile, it doesn't switch.
|
||||
func saveProfileRef(opts *LoginOptions, fopts *cmdutil.FormatOptions, f *cmdutil.Factory, mutate func(*config.Profile), mode string, user *sdk.AuthUser) error {
|
||||
cfg, err := f.Config()
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -255,15 +331,19 @@ func saveProfileRef(opts *LoginOptions, fopts *cmdutil.FormatOptions, f *cmdutil
|
||||
if cfg.Profiles == nil {
|
||||
cfg.Profiles = map[string]config.Profile{}
|
||||
}
|
||||
cfg.Profiles[opts.Profile] = *prof
|
||||
cfg.CurrentProfile = opts.Profile
|
||||
prof := cfg.Profiles[opts.Profile] // existing record (Host, User, TenantID)
|
||||
mutate(&prof)
|
||||
cfg.Profiles[opts.Profile] = prof
|
||||
if err := config.Save(cfg); err != nil {
|
||||
return cmdutil.Wrapf(cmdutil.CodeLocalFileIO, err, "save config")
|
||||
}
|
||||
if fopts.WantsJSON() {
|
||||
result := loginResult{Profile: opts.Profile, Host: opts.Host, Mode: ModeAPIKey}
|
||||
// mode reflects the credential actually stored (passed by the caller),
|
||||
// not whether the server happened to return a user — an API-key login
|
||||
// validates via /auth/me and DOES get a user, so deriving mode from
|
||||
// user != nil would mislabel it as bearer.
|
||||
result := loginResult{Profile: opts.Profile, Host: opts.Host, Mode: mode}
|
||||
if user != nil {
|
||||
result.Mode = ModeBearer
|
||||
result.User = user.Email
|
||||
result.TenantID = user.TenantID
|
||||
}
|
||||
|
||||
+107
-13
@@ -2,6 +2,7 @@ package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
@@ -50,37 +51,49 @@ func newTestFactoryWithConfig(t *testing.T, p prompt.Prompter) (*cmdutil.Factory
|
||||
}, store
|
||||
}
|
||||
|
||||
// seedActiveProfile writes an active profile to the (XDG-isolated) config so
|
||||
// runLogin can resolve host/name from it - `auth login` authenticates the
|
||||
// already-existing active profile rather than creating one. Returns nothing;
|
||||
// callers read back via f.Config() to assert merge behavior.
|
||||
func seedActiveProfile(t *testing.T, name string, prof config.Profile) {
|
||||
t.Helper()
|
||||
cfg := &config.Config{
|
||||
CurrentProfile: name,
|
||||
Profiles: map[string]config.Profile{name: prof},
|
||||
}
|
||||
require.NoError(t, config.Save(cfg))
|
||||
}
|
||||
|
||||
func TestRunLogin_PasswordMode(t *testing.T) {
|
||||
iostreams.SetForTest(t)
|
||||
f, store := newTestFactoryWithConfig(t, scriptedPrompter{email: "a@b.c", password: "secret"})
|
||||
seedActiveProfile(t, "prod", config.Profile{Host: "https://kb.example.com"})
|
||||
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",
|
||||
Profile: "prod",
|
||||
}
|
||||
require.NoError(t, runLogin(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, svc))
|
||||
require.NoError(t, runLogin(context.Background(), &LoginOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, 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)
|
||||
|
||||
cfg, _ := f.Config()
|
||||
assert.Equal(t, "https://kb.example.com", cfg.Profiles["prod"].Host, "host must be preserved from the seeded profile")
|
||||
}
|
||||
|
||||
func TestRunLogin_WithToken(t *testing.T) {
|
||||
iostreams.SetForTest(t)
|
||||
f, store := newTestFactoryWithConfig(t, prompt.AgentPrompter{})
|
||||
seedActiveProfile(t, "ci", config.Profile{Host: "https://kb.example.com"})
|
||||
restore := stubAPIKeyValidator(func(_ context.Context, _, _ string) (*sdk.AuthUser, error) {
|
||||
return &sdk.AuthUser{ID: "u1", Email: "ci@example.com", TenantID: 7}, nil
|
||||
})
|
||||
defer restore()
|
||||
opts := &LoginOptions{
|
||||
Host: "https://kb.example.com",
|
||||
Profile: "ci",
|
||||
WithToken: true,
|
||||
StdinReader: strings.NewReader(" sk-1234 \n"),
|
||||
}
|
||||
@@ -90,11 +103,36 @@ func TestRunLogin_WithToken(t *testing.T) {
|
||||
cfg, _ := f.Config()
|
||||
assert.Equal(t, "ci@example.com", cfg.Profiles["ci"].User, "validator-returned user should be persisted")
|
||||
assert.Equal(t, uint64(7), cfg.Profiles["ci"].TenantID)
|
||||
assert.Equal(t, "https://kb.example.com", cfg.Profiles["ci"].Host, "host preserved from seeded profile")
|
||||
}
|
||||
|
||||
func TestRunLogin_WithToken_JSONReportsAPIKeyMode(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
f, _ := newTestFactoryWithConfig(t, prompt.AgentPrompter{})
|
||||
seedActiveProfile(t, "ci", config.Profile{Host: "https://kb.example.com"})
|
||||
restore := stubAPIKeyValidator(func(_ context.Context, _, _ string) (*sdk.AuthUser, error) {
|
||||
// API-key validation hits /auth/me, which DOES return a user. mode
|
||||
// must still be reported as api-key (derived from credential type,
|
||||
// not from "did the server return a user").
|
||||
return &sdk.AuthUser{ID: "u1", Email: "ci@example.com", TenantID: 7}, nil
|
||||
})
|
||||
defer restore()
|
||||
opts := &LoginOptions{WithToken: true, StdinReader: strings.NewReader("sk-1234")}
|
||||
require.NoError(t, runLogin(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, f, nil))
|
||||
|
||||
var env struct {
|
||||
Data struct {
|
||||
Mode string `json:"mode"`
|
||||
} `json:"data"`
|
||||
}
|
||||
require.NoError(t, json.Unmarshal(out.Bytes(), &env))
|
||||
assert.Equal(t, "api-key", env.Data.Mode, "api-key login must report mode=api-key, not bearer")
|
||||
}
|
||||
|
||||
func TestRunLogin_WithToken_ServerRejects(t *testing.T) {
|
||||
iostreams.SetForTest(t)
|
||||
f, _ := newTestFactoryWithConfig(t, prompt.AgentPrompter{})
|
||||
seedActiveProfile(t, "ci", config.Profile{Host: "https://kb.example.com"})
|
||||
restore := stubAPIKeyValidator(func(_ context.Context, _, _ string) (*sdk.AuthUser, error) {
|
||||
// Use the SDK-format HTTP error message so ClassifyHTTPError detects
|
||||
// this as an HTTP 401, not a transport/network failure.
|
||||
@@ -102,8 +140,6 @@ func TestRunLogin_WithToken_ServerRejects(t *testing.T) {
|
||||
})
|
||||
defer restore()
|
||||
opts := &LoginOptions{
|
||||
Host: "https://kb.example.com",
|
||||
Profile: "ci",
|
||||
WithToken: true,
|
||||
StdinReader: strings.NewReader("sk-bad"),
|
||||
}
|
||||
@@ -126,6 +162,7 @@ func stubAPIKeyValidator(fn apiKeyValidator) func() {
|
||||
func TestRunLogin_WithToken_Empty(t *testing.T) {
|
||||
iostreams.SetForTest(t)
|
||||
f, _ := newTestFactoryWithConfig(t, prompt.AgentPrompter{})
|
||||
seedActiveProfile(t, "ci", config.Profile{Host: "https://kb.example.com"})
|
||||
// Validator must NOT be called when stdin is empty - verify by setting
|
||||
// a panic-on-call sentinel.
|
||||
restore := stubAPIKeyValidator(func(_ context.Context, _, _ string) (*sdk.AuthUser, error) {
|
||||
@@ -134,8 +171,6 @@ func TestRunLogin_WithToken_Empty(t *testing.T) {
|
||||
})
|
||||
defer restore()
|
||||
opts := &LoginOptions{
|
||||
Host: "https://kb.example.com",
|
||||
Profile: "ci",
|
||||
WithToken: true,
|
||||
StdinReader: strings.NewReader(""),
|
||||
}
|
||||
@@ -147,7 +182,10 @@ func TestRunLogin_WithToken_Empty(t *testing.T) {
|
||||
func TestRunLogin_BadHost(t *testing.T) {
|
||||
iostreams.SetForTest(t)
|
||||
f, _ := newTestFactoryWithConfig(t, prompt.AgentPrompter{})
|
||||
err := runLogin(context.Background(), &LoginOptions{Host: "ftp://nope"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, nil)
|
||||
// A non-http host stored on the active profile must be rejected by the
|
||||
// post-resolution validateHost check (config corruption guard).
|
||||
seedActiveProfile(t, "bad", config.Profile{Host: "ftp://nope"})
|
||||
err := runLogin(context.Background(), &LoginOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, nil)
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "input.invalid_argument")
|
||||
}
|
||||
@@ -155,8 +193,9 @@ func TestRunLogin_BadHost(t *testing.T) {
|
||||
func TestRunLogin_LoginRefused(t *testing.T) {
|
||||
iostreams.SetForTest(t)
|
||||
f, _ := newTestFactoryWithConfig(t, scriptedPrompter{email: "a@b.c", password: "x"})
|
||||
seedActiveProfile(t, "p", config.Profile{Host: "https://x"})
|
||||
svc := &fakeLoginService{resp: &sdk.LoginResponse{Success: false, Message: "bad password"}}
|
||||
err := runLogin(context.Background(), &LoginOptions{Host: "https://x", Profile: "p"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, svc)
|
||||
err := runLogin(context.Background(), &LoginOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, svc)
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "auth.bad_credential")
|
||||
}
|
||||
@@ -168,3 +207,58 @@ func TestValidateHost(t *testing.T) {
|
||||
require.Error(t, validateHost("ftp://x"))
|
||||
require.Error(t, validateHost("not a url"))
|
||||
}
|
||||
|
||||
// TestLogin_NoHostNoName asserts the --host / --name flags are gone: `auth
|
||||
// login` now authenticates the active profile (create it via `profile add`).
|
||||
func TestLogin_NoHostNoName(t *testing.T) {
|
||||
iostreams.SetForTest(t)
|
||||
f, _ := newTestFactoryWithConfig(t, prompt.AgentPrompter{})
|
||||
cmd := NewCmdLogin(f, nil)
|
||||
assert.Nil(t, cmd.Flags().Lookup("host"), "--host flag must be removed")
|
||||
assert.Nil(t, cmd.Flags().Lookup("name"), "--name flag must be removed")
|
||||
assert.NotNil(t, cmd.Flags().Lookup("with-token"), "--with-token must remain")
|
||||
}
|
||||
|
||||
// TestLogin_NoActiveProfile_Errors asserts that with no active profile
|
||||
// configured, login returns a clear auth.unauthenticated error pointing the
|
||||
// user at `profile add`.
|
||||
func TestLogin_NoActiveProfile_Errors(t *testing.T) {
|
||||
iostreams.SetForTest(t)
|
||||
f, _ := newTestFactoryWithConfig(t, prompt.AgentPrompter{})
|
||||
// No seedActiveProfile: empty config.
|
||||
err := runLogin(context.Background(), &LoginOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, nil)
|
||||
require.Error(t, err)
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
assert.Equal(t, cmdutil.CodeAuthUnauthenticated, typed.Code)
|
||||
assert.Contains(t, err.Error(), "profile add")
|
||||
}
|
||||
|
||||
// TestLogin_UsesActiveProfileHost asserts login persists credentials under the
|
||||
// active profile using that profile's stored host, and that an existing User
|
||||
// is NOT clobbered when the server (API-key validator) returns it unchanged.
|
||||
func TestLogin_UsesActiveProfileHost(t *testing.T) {
|
||||
iostreams.SetForTest(t)
|
||||
f, store := newTestFactoryWithConfig(t, prompt.AgentPrompter{})
|
||||
// Pre-seed "prod" with a host AND a user that must survive re-login.
|
||||
seedActiveProfile(t, "prod", config.Profile{Host: "https://prod.example.com", User: "existing@owner.com"})
|
||||
restore := stubAPIKeyValidator(func(_ context.Context, host, _ string) (*sdk.AuthUser, error) {
|
||||
assert.Equal(t, "https://prod.example.com", host, "validator must be called with the active profile's host")
|
||||
// Server returns nil user (e.g. /auth/me gave no email) - must NOT
|
||||
// wipe the existing User.
|
||||
return &sdk.AuthUser{}, nil
|
||||
})
|
||||
defer restore()
|
||||
opts := &LoginOptions{WithToken: true, StdinReader: strings.NewReader("sk-prod")}
|
||||
require.NoError(t, runLogin(context.Background(), opts, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, nil))
|
||||
|
||||
got, _ := store.Get("prod", "api_key")
|
||||
assert.Equal(t, "sk-prod", got, "api key must be stored under the active profile")
|
||||
|
||||
cfg, _ := f.Config()
|
||||
prof := cfg.Profiles["prod"]
|
||||
assert.Equal(t, "https://prod.example.com", prof.Host, "host must be preserved, not clobbered")
|
||||
assert.Equal(t, "existing@owner.com", prof.User, "existing User must NOT be wiped when server returns none")
|
||||
assert.NotEmpty(t, prof.APIKeyRef, "api-key ref must be set")
|
||||
assert.Equal(t, "prod", cfg.CurrentProfile, "active profile unchanged")
|
||||
}
|
||||
|
||||
+10
-32
@@ -13,9 +13,8 @@ import (
|
||||
)
|
||||
|
||||
type LogoutOptions struct {
|
||||
Name string // --name: target a specific profile (default: current)
|
||||
All bool // --all: clear every profile
|
||||
Yes bool // sourced from the global -y/--yes persistent flag
|
||||
All bool // --all: clear every profile
|
||||
Yes bool // sourced from the global -y/--yes persistent flag
|
||||
DryRun bool
|
||||
}
|
||||
|
||||
@@ -43,8 +42,8 @@ them with --all) and drop the profile entry from ~/.config/weknora/config.yaml.
|
||||
Note: this does NOT revoke the credential server-side - for API keys, you
|
||||
must rotate them in the server UI; for JWT, the token will continue to be
|
||||
accepted until it expires.`,
|
||||
Example: ` weknora auth logout # current profile
|
||||
weknora auth logout --name staging # specific profile
|
||||
Example: ` weknora auth logout # active profile
|
||||
weknora --profile staging auth logout # specific profile
|
||||
weknora auth logout --all`,
|
||||
Args: cobra.NoArgs,
|
||||
RunE: func(c *cobra.Command, _ []string) error {
|
||||
@@ -64,16 +63,11 @@ accepted until it expires.`,
|
||||
if len(cfg.Profiles) == 0 {
|
||||
return cmdutil.NewError(cmdutil.CodeAuthUnauthenticated, "no profiles configured; nothing to log out")
|
||||
}
|
||||
if opts.Name != "" {
|
||||
if err := cmdutil.ValidateProfileName(opts.Name); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if _, err := pickLogoutTargets(opts, cfg); err != nil {
|
||||
return err
|
||||
}
|
||||
if opts.DryRun {
|
||||
planArgs := map[string]any{"name": opts.Name}
|
||||
planArgs := map[string]any{"profile": cfg.CurrentProfile}
|
||||
if opts.All {
|
||||
planArgs = map[string]any{"all": true}
|
||||
}
|
||||
@@ -87,17 +81,15 @@ accepted until it expires.`,
|
||||
return runLogout(opts, fopts, f)
|
||||
},
|
||||
}
|
||||
cmd.Flags().StringVar(&opts.Name, "name", "", "Profile to log out (defaults to the current profile)")
|
||||
cmd.Flags().BoolVar(&opts.All, "all", false, "Log out of every configured profile")
|
||||
cmdutil.AddFormatFlag(cmd, authLogoutFields...)
|
||||
cmdutil.AddDryRunFlag(cmd, &opts.DryRun)
|
||||
cmd.MarkFlagsMutuallyExclusive("name", "all")
|
||||
cmdutil.SetRisk(cmd, "auth.logout")
|
||||
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
|
||||
UsedFor: "clear stored credentials for one profile (or all) and remove the profile from config",
|
||||
UsedFor: "clear stored credentials for the active profile (or all) and remove the profile from config",
|
||||
Examples: []string{
|
||||
"weknora auth logout",
|
||||
"weknora auth logout --name staging",
|
||||
"weknora --profile staging auth logout",
|
||||
"weknora auth logout --all",
|
||||
},
|
||||
Warnings: []string{
|
||||
@@ -116,15 +108,6 @@ func runLogout(opts *LogoutOptions, fopts *cmdutil.FormatOptions, f *cmdutil.Fac
|
||||
if len(cfg.Profiles) == 0 {
|
||||
return cmdutil.NewError(cmdutil.CodeAuthUnauthenticated, "no profiles configured; nothing to log out")
|
||||
}
|
||||
// Reject shell-metacharacter names so opts.Name is safe to interpolate
|
||||
// into envelope.error.retry_command. Validation is name-only — the
|
||||
// profile may or may not exist in cfg.Profiles; the existence check
|
||||
// happens in pickLogoutTargets.
|
||||
if opts.Name != "" {
|
||||
if err := cmdutil.ValidateProfileName(opts.Name); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
targets, err := pickLogoutTargets(opts, cfg)
|
||||
if err != nil {
|
||||
@@ -136,10 +119,8 @@ func runLogout(opts *LogoutOptions, fopts *cmdutil.FormatOptions, f *cmdutil.Fac
|
||||
retryCmd := "weknora auth logout -y"
|
||||
if opts.All {
|
||||
retryCmd = "weknora auth logout --all -y"
|
||||
} else if opts.Name != "" {
|
||||
retryCmd = fmt.Sprintf("weknora auth logout --name %s -y", opts.Name)
|
||||
}
|
||||
if err := cmdutil.ConfirmDestructive(f.Prompter(), opts.Yes, fopts.WantsJSON(), "auth credentials", scope, "auth.logout", retryCmd); err != nil {
|
||||
if err := cmdutil.ConfirmDestructive(f.Prompter(), opts.Yes, fopts.WantsJSON(), "delete", "auth credentials", scope, "auth.logout", retryCmd); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -178,13 +159,10 @@ func pickLogoutTargets(opts *LogoutOptions, cfg *config.Config) ([]string, error
|
||||
}
|
||||
return names, nil
|
||||
}
|
||||
name := opts.Name
|
||||
if name == "" {
|
||||
name = cfg.CurrentProfile
|
||||
}
|
||||
name := cfg.CurrentProfile
|
||||
if name == "" {
|
||||
return nil, cmdutil.NewError(cmdutil.CodeInputMissingFlag,
|
||||
"no current profile set; pass --name <profile> or --all")
|
||||
"no active profile set; use the global --profile <profile> or --all")
|
||||
}
|
||||
if _, ok := cfg.Profiles[name]; !ok {
|
||||
return nil, cmdutil.NewError(cmdutil.CodeLocalProfileNotFound,
|
||||
|
||||
+20
-18
@@ -1,7 +1,6 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
@@ -62,24 +61,28 @@ func TestLogout_CurrentProfile(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestLogout_NamedContext(t *testing.T) {
|
||||
// TestLogout_ActiveProfileViaOverride exercises targeting a non-default
|
||||
// profile. Production resolves this via the global --profile flag (which
|
||||
// rewrites cfg.CurrentProfile in Factory.Config); here we simulate that by
|
||||
// setting CurrentProfile=staging directly, since runLogout's single target is
|
||||
// the active profile.
|
||||
func TestLogout_ActiveProfileViaOverride(t *testing.T) {
|
||||
isolateConfig(t)
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
store := secrets.NewMemStore()
|
||||
require.NoError(t, store.Set("staging", "api_key", "sk-staging"))
|
||||
|
||||
cfg := &config.Config{
|
||||
CurrentProfile: "prod",
|
||||
CurrentProfile: "staging", // global --profile staging resolves to this
|
||||
Profiles: map[string]config.Profile{
|
||||
"prod": {Host: "https://prod", TokenRef: "tok"},
|
||||
"staging": {Host: "https://staging", APIKeyRef: store.Ref("staging", "api_key")},
|
||||
},
|
||||
}
|
||||
require.NoError(t, runLogout(&LogoutOptions{Name: "staging", Yes: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, newLogoutFactory(t, cfg, store)))
|
||||
require.NoError(t, runLogout(&LogoutOptions{Yes: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, newLogoutFactory(t, cfg, store)))
|
||||
|
||||
assert.Equal(t, "prod", cfg.CurrentProfile, "current_profile untouched when removing other")
|
||||
assert.NotContains(t, cfg.Profiles, "staging")
|
||||
assert.Contains(t, cfg.Profiles, "prod")
|
||||
assert.NotContains(t, cfg.Profiles, "staging", "active profile (staging) is the target")
|
||||
assert.Contains(t, cfg.Profiles, "prod", "non-target profile untouched")
|
||||
}
|
||||
|
||||
func TestLogout_All(t *testing.T) {
|
||||
@@ -110,14 +113,16 @@ func TestLogout_NoProfiles(t *testing.T) {
|
||||
assert.Equal(t, cmdutil.CodeAuthUnauthenticated, typed.Code)
|
||||
}
|
||||
|
||||
func TestLogout_UnknownName(t *testing.T) {
|
||||
// TestLogout_ActiveProfileMissing covers the corrupt-config case where the
|
||||
// active profile name (e.g. set via --profile ghost) has no matching entry.
|
||||
func TestLogout_ActiveProfileMissing(t *testing.T) {
|
||||
isolateConfig(t)
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
cfg := &config.Config{
|
||||
CurrentProfile: "prod",
|
||||
CurrentProfile: "ghost", // points at a non-existent entry
|
||||
Profiles: map[string]config.Profile{"prod": {Host: "https://prod"}},
|
||||
}
|
||||
err := runLogout(&LogoutOptions{Name: "ghost"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, 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)
|
||||
@@ -137,16 +142,13 @@ func TestLogout_NoCurrentNoFlag(t *testing.T) {
|
||||
assert.Equal(t, cmdutil.CodeInputMissingFlag, typed.Code)
|
||||
}
|
||||
|
||||
// TestLogout_Cobra exercises the cobra layer for the mutually-exclusive
|
||||
// --name + --all flag pair.
|
||||
func TestLogout_Cobra_FlagsMutuallyExclusive(t *testing.T) {
|
||||
// TestLogout_NoNameFlag asserts the --name flag is gone (logout now targets
|
||||
// the active profile / global --profile) while --all stands alone.
|
||||
func TestLogout_NoNameFlag(t *testing.T) {
|
||||
isolateConfig(t)
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
cfg := &config.Config{Profiles: map[string]config.Profile{"a": {}}}
|
||||
cmd := NewCmdLogout(newLogoutFactory(t, cfg, secrets.NewMemStore()))
|
||||
cmd.SetContext(context.Background())
|
||||
cmd.SetArgs([]string{"--name", "a", "--all"})
|
||||
cmd.SilenceErrors = true
|
||||
cmd.SilenceUsage = true
|
||||
require.Error(t, cmd.Execute())
|
||||
assert.Nil(t, cmd.Flags().Lookup("name"), "--name flag must be removed")
|
||||
assert.NotNil(t, cmd.Flags().Lookup("all"), "--all flag must remain")
|
||||
}
|
||||
|
||||
+10
-14
@@ -12,7 +12,6 @@ import (
|
||||
)
|
||||
|
||||
type RefreshOptions struct {
|
||||
Name string // --name: target profile (defaults to current)
|
||||
DryRun bool
|
||||
}
|
||||
|
||||
@@ -45,8 +44,8 @@ Both new tokens replace the existing entries in the OS keyring.
|
||||
|
||||
API-key profiles are rejected with input.invalid_argument - they have no
|
||||
refresh semantic. Rotate the key in the server UI instead.`,
|
||||
Example: ` weknora auth refresh # refresh the current profile
|
||||
weknora auth refresh --name staging # refresh a specific profile`,
|
||||
Example: ` weknora auth refresh # refresh the active profile
|
||||
weknora --profile staging auth refresh # refresh a specific profile`,
|
||||
Args: cobra.NoArgs,
|
||||
RunE: func(c *cobra.Command, _ []string) error {
|
||||
fopts, err := cmdutil.CheckFormatFlag(c)
|
||||
@@ -61,13 +60,10 @@ refresh semantic. Rotate the key in the server UI instead.`,
|
||||
if cfgErr != nil {
|
||||
return cfgErr
|
||||
}
|
||||
name := opts.Name
|
||||
if name == "" {
|
||||
name = cfg.CurrentProfile
|
||||
}
|
||||
name := cfg.CurrentProfile
|
||||
if name == "" {
|
||||
return cmdutil.NewError(cmdutil.CodeAuthUnauthenticated,
|
||||
"no current profile configured; run `weknora auth login` to set one up")
|
||||
"no active profile configured; run `weknora auth login` to set one up")
|
||||
}
|
||||
prof, ok := cfg.Profiles[name]
|
||||
if !ok {
|
||||
@@ -98,9 +94,12 @@ refresh semantic. Rotate the key in the server UI instead.`,
|
||||
return runRefresh(c.Context(), opts, fopts, f, defaultRefresher)
|
||||
},
|
||||
}
|
||||
cmd.Flags().StringVar(&opts.Name, "name", "", "Profile to refresh (defaults to the current profile)")
|
||||
cmdutil.AddFormatFlag(cmd, authRefreshFields...)
|
||||
cmdutil.AddDryRunFlag(cmd, &opts.DryRun)
|
||||
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
|
||||
UsedFor: "Renew the JWT access token for the active profile (override with the global --profile) using the stored refresh token. API-key profiles are rejected.",
|
||||
Output: "envelope.data has profile name that was refreshed",
|
||||
})
|
||||
return cmd
|
||||
}
|
||||
|
||||
@@ -116,13 +115,10 @@ func runRefresh(ctx context.Context, opts *RefreshOptions, fopts *cmdutil.Format
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
name := opts.Name
|
||||
if name == "" {
|
||||
name = cfg.CurrentProfile
|
||||
}
|
||||
name := cfg.CurrentProfile
|
||||
if name == "" {
|
||||
return cmdutil.NewError(cmdutil.CodeAuthUnauthenticated,
|
||||
"no current profile configured; run `weknora auth login` to set one up")
|
||||
"no active profile configured; run `weknora auth login` to set one up")
|
||||
}
|
||||
c, ok := cfg.Profiles[name]
|
||||
if !ok {
|
||||
|
||||
@@ -81,13 +81,18 @@ func TestRefresh_Happy(t *testing.T) {
|
||||
assert.Equal(t, "new-refresh", gotRefresh)
|
||||
}
|
||||
|
||||
func TestRefresh_NamedContext(t *testing.T) {
|
||||
// TestRefresh_ActiveProfileViaOverride exercises refreshing a non-default
|
||||
// profile. Production resolves this via the global --profile flag (which
|
||||
// rewrites cfg.CurrentProfile in Factory.Config); here we set
|
||||
// CurrentProfile=staging directly, since runRefresh's target is the active
|
||||
// profile.
|
||||
func TestRefresh_ActiveProfileViaOverride(t *testing.T) {
|
||||
iostreams.SetForTest(t)
|
||||
store := secrets.NewMemStore()
|
||||
require.NoError(t, store.Set("staging", "refresh", "stg-refresh"))
|
||||
|
||||
cfg := &config.Config{
|
||||
CurrentProfile: "prod",
|
||||
CurrentProfile: "staging", // global --profile staging resolves to this
|
||||
Profiles: map[string]config.Profile{
|
||||
"prod": {Host: "https://prod", TokenRef: "mem://prod/access", RefreshRef: "mem://prod/refresh"},
|
||||
"staging": {Host: "https://stg", TokenRef: "mem://staging/access", RefreshRef: "mem://staging/refresh"},
|
||||
@@ -97,15 +102,25 @@ func TestRefresh_NamedContext(t *testing.T) {
|
||||
svc := &fakeRefreshService{resp: &sdk.RefreshTokenResponse{
|
||||
Success: true, AccessToken: "new-stg-access", RefreshToken: "new-stg-refresh",
|
||||
}}
|
||||
require.NoError(t, runRefresh(context.Background(), &RefreshOptions{Name: "staging"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, stubSvc(svc)))
|
||||
require.NoError(t, runRefresh(context.Background(), &RefreshOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, f, stubSvc(svc)))
|
||||
|
||||
assert.Equal(t, "stg-refresh", svc.gotTok, "--name=staging must refresh the staging profile, not current")
|
||||
// current is untouched
|
||||
assert.Equal(t, "stg-refresh", svc.gotTok, "active profile staging must be refreshed")
|
||||
// prod (non-active) is untouched
|
||||
if v, _ := store.Get("prod", "access"); v != "" {
|
||||
t.Errorf("prod must not have been touched, got %q", v)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRefresh_NoNameFlag asserts the --name flag is gone; refresh targets the
|
||||
// active profile (override via the global --profile).
|
||||
func TestRefresh_NoNameFlag(t *testing.T) {
|
||||
iostreams.SetForTest(t)
|
||||
cfg := &config.Config{Profiles: map[string]config.Profile{"a": {Host: "https://a"}}}
|
||||
f := newRefreshFactory(t, cfg, secrets.NewMemStore())
|
||||
cmd := NewCmdRefresh(f)
|
||||
assert.Nil(t, cmd.Flags().Lookup("name"), "--name flag must be removed")
|
||||
}
|
||||
|
||||
func TestRefresh_NoCurrentProfile(t *testing.T) {
|
||||
iostreams.SetForTest(t)
|
||||
f := newRefreshFactory(t, &config.Config{}, secrets.NewMemStore())
|
||||
|
||||
@@ -65,6 +65,11 @@ usually only surfaces a hard auth failure.`,
|
||||
},
|
||||
}
|
||||
cmdutil.AddFormatFlag(cmd, authStatusFields...)
|
||||
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
|
||||
UsedFor: "show the active profile, the authenticated principal, and token state",
|
||||
Examples: []string{"weknora auth status", "weknora auth status --jq .data.tenant_id"},
|
||||
Output: "envelope.data is {profile, host, user, tenant, ...}; exit 3 if unauthenticated",
|
||||
})
|
||||
return cmd
|
||||
}
|
||||
|
||||
|
||||
+28
-2
@@ -55,11 +55,37 @@ to see which mode each profile uses, and construct the matching HTTP header:
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fopts.ResolveDefault(iostreams.IO.IsStdoutTTY())
|
||||
// `auth token` is a scalar scripting helper (WEKNORA_TOKEN=$(...)),
|
||||
// so it defaults to the raw token — overriding the global json
|
||||
// default (gh auth token does the same; cf. doc download streaming
|
||||
// raw bytes). Explicit --format json / WEKNORA_FORMAT=json still
|
||||
// emit the {token,mode,profile} envelope.
|
||||
fopts.FromEnv()
|
||||
if fopts.Mode == "" {
|
||||
// --jq implies JSON (it filters the envelope); without it,
|
||||
// default to the raw token for clean $(...) capture.
|
||||
if fopts.JQ != "" {
|
||||
fopts.Mode = cmdutil.FormatJSON
|
||||
} else {
|
||||
fopts.Mode = cmdutil.FormatText
|
||||
}
|
||||
}
|
||||
return runToken(f, fopts)
|
||||
},
|
||||
}
|
||||
cmdutil.AddFormatFlag(cmd, authTokenFields...)
|
||||
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
|
||||
UsedFor: "print the active profile's raw credential to stdout for shell capture",
|
||||
Examples: []string{
|
||||
"WEKNORA_TOKEN=$(weknora auth token)",
|
||||
"weknora auth token --profile staging",
|
||||
"weknora auth token --format json",
|
||||
},
|
||||
Output: "raw token on stdout (no envelope, no trailing newline) by default; --format json emits {token, mode, profile}",
|
||||
Warnings: []string{
|
||||
"default output is the bare token, NOT the JSON envelope — it is a scripting helper (cf. `gh auth token`)",
|
||||
},
|
||||
})
|
||||
return cmd
|
||||
}
|
||||
|
||||
@@ -74,7 +100,7 @@ func runToken(f *cmdutil.Factory, fopts *cmdutil.FormatOptions) error {
|
||||
}
|
||||
if profileName == "" {
|
||||
return cmdutil.NewError(cmdutil.CodeAuthUnauthenticated,
|
||||
"no current profile configured")
|
||||
"no active profile configured")
|
||||
}
|
||||
ctx, ok := cfg.Profiles[profileName]
|
||||
if !ok {
|
||||
|
||||
@@ -23,6 +23,65 @@ func tokenTestFactory(t *testing.T, cfg *config.Config, store *secrets.MemStore)
|
||||
return f
|
||||
}
|
||||
|
||||
// TestAuthToken_DefaultIsRawToken locks the scripting contract: with no
|
||||
// explicit --format, `weknora auth token` emits the raw token (so
|
||||
// WEKNORA_TOKEN=$(weknora auth token) works), NOT the JSON envelope — even
|
||||
// though the global --format default is json. Explicit --format json still
|
||||
// emits the {token,mode,profile} envelope (covered by the JSON test below).
|
||||
func TestAuthToken_DefaultIsRawToken(t *testing.T) {
|
||||
cfg := &config.Config{
|
||||
CurrentProfile: "prod",
|
||||
Profiles: map[string]config.Profile{
|
||||
"prod": {Host: "https://kb.example.com", TokenRef: "prod:access"},
|
||||
},
|
||||
}
|
||||
store := secrets.NewMemStore()
|
||||
_ = store.Set("prod", "access", "jwt-default-xyz")
|
||||
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
cmd := NewCmdToken(tokenTestFactory(t, cfg, store))
|
||||
cmd.PersistentFlags().String("format", "", "") // mirror the root persistent flag, unset
|
||||
cmd.SetArgs([]string{})
|
||||
if err := cmd.Execute(); err != nil {
|
||||
t.Fatalf("execute: %v", err)
|
||||
}
|
||||
if got := out.String(); got != "jwt-default-xyz" {
|
||||
t.Errorf("default output must be the raw token (not an envelope); got %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAuthToken_JQImpliesJSON: --jq filters the envelope, so passing it without
|
||||
// an explicit --format must resolve to JSON (not the raw-token default), else
|
||||
// the filter would be silently dropped.
|
||||
func TestAuthToken_JQImpliesJSON(t *testing.T) {
|
||||
cfg := &config.Config{
|
||||
CurrentProfile: "prod",
|
||||
Profiles: map[string]config.Profile{
|
||||
"prod": {Host: "https://kb.example.com", TokenRef: "prod:access"},
|
||||
},
|
||||
}
|
||||
store := secrets.NewMemStore()
|
||||
_ = store.Set("prod", "access", "jwt-jq-xyz")
|
||||
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
cmd := NewCmdToken(tokenTestFactory(t, cfg, store))
|
||||
cmd.PersistentFlags().String("format", "", "")
|
||||
cmd.PersistentFlags().StringP("jq", "q", "", "")
|
||||
// Structural projection: proves jq ran on the JSON envelope (object out),
|
||||
// not the raw-token text path (which would print the bare string).
|
||||
cmd.SetArgs([]string{"--jq", ".data | {token}"})
|
||||
if err := cmd.Execute(); err != nil {
|
||||
t.Fatalf("execute: %v", err)
|
||||
}
|
||||
var got map[string]any
|
||||
if err := json.Unmarshal(out.Bytes(), &got); err != nil {
|
||||
t.Fatalf("--jq without --format must filter the JSON envelope, got non-JSON %q: %v", out.String(), err)
|
||||
}
|
||||
if got["token"] != "jwt-jq-xyz" {
|
||||
t.Errorf("jq projection wrong: %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthToken_BearerMode_PlainOutput(t *testing.T) {
|
||||
cfg := &config.Config{
|
||||
CurrentProfile: "prod",
|
||||
|
||||
+25
-14
@@ -13,6 +13,7 @@ import (
|
||||
type AddOptions struct {
|
||||
Host string
|
||||
User string
|
||||
Use bool // --use: switch to this profile after adding
|
||||
DryRun bool
|
||||
}
|
||||
|
||||
@@ -32,24 +33,25 @@ type addResult struct {
|
||||
|
||||
// NewCmdAdd builds `weknora profile add`. Registers a *credentialless*
|
||||
// connection target - host + optional user only. Credentials for the new
|
||||
// profile are attached separately with `weknora auth login --name <n>`,
|
||||
// separating "where" the CLI talks to (the host) and "how" it authenticates
|
||||
// (the credential). If you want one command for both, run
|
||||
// `weknora auth login --name <n> --host <h>` instead.
|
||||
// profile are attached separately by making it active and running
|
||||
// `weknora auth login`, separating "where" the CLI talks to (the host) and
|
||||
// "how" it authenticates (the credential). Pass --use to switch to the new
|
||||
// profile immediately, then run `weknora auth login`.
|
||||
func NewCmdAdd(f *cmdutil.Factory) *cobra.Command {
|
||||
opts := &AddOptions{}
|
||||
cmd := &cobra.Command{
|
||||
Use: "add <name>",
|
||||
Short: "Register a new profile (host without credentials)",
|
||||
Long: `Add a new profile entry to config.yaml. Stores host (and optionally
|
||||
user) but does NOT prompt for credentials. Use ` + "`weknora auth login --name <n>`" + ` to
|
||||
attach credentials in a single step instead, or run ` + "`weknora auth login --name <n>`" + ` after
|
||||
` + "`weknora profile add`" + ` to fill them in.
|
||||
user) but does NOT prompt for credentials. To attach credentials, make the
|
||||
profile active (` + "`weknora profile use <n>`" + `, or ` + "`profile add <n> --use`" + `) and run
|
||||
` + "`weknora auth login`" + `.
|
||||
|
||||
The first profile added is auto-selected as the current profile. Subsequent
|
||||
adds leave the current profile untouched.`,
|
||||
adds leave the current profile untouched unless --use is passed.`,
|
||||
Example: ` weknora profile add staging --host https://staging.example.com
|
||||
weknora profile add prod --host https://prod.example.com --user alice@example.com`,
|
||||
weknora profile add prod --host https://prod.example.com --user alice@example.com
|
||||
weknora profile add prod --host https://prod.example.com --use # switch to it now`,
|
||||
Args: cobra.ExactArgs(1),
|
||||
RunE: func(c *cobra.Command, args []string) error {
|
||||
fopts, err := cmdutil.CheckFormatFlag(c)
|
||||
@@ -93,9 +95,15 @@ adds leave the current profile untouched.`,
|
||||
}
|
||||
cmd.Flags().StringVar(&opts.Host, "host", "", "Server base URL, e.g. https://kb.example.com (required)")
|
||||
cmd.Flags().StringVar(&opts.User, "user", "", "Account email shown in 'profile list' (optional, cosmetic only)")
|
||||
cmd.Flags().BoolVar(&opts.Use, "use", false, "Switch to this profile after adding it")
|
||||
cmdutil.AddFormatFlag(cmd, profileAddFields...)
|
||||
cmdutil.AddDryRunFlag(cmd, &opts.DryRun)
|
||||
_ = cmd.MarkFlagRequired("host")
|
||||
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
|
||||
UsedFor: "Register a new profile (connection target) with a name and host URL. Does not store credentials; make it active (--use, or `profile use <n>`) and run `auth login` afterwards to authenticate.",
|
||||
RequiredFlags: []string{"<name> (positional)", "--host"},
|
||||
Output: "envelope.data has name, host, user, current",
|
||||
})
|
||||
return cmd
|
||||
}
|
||||
|
||||
@@ -133,7 +141,10 @@ func runAddWithConfig(opts *AddOptions, fopts *cmdutil.FormatOptions, name, host
|
||||
}
|
||||
cfg.Profiles[name] = config.Profile{Host: host, User: opts.User}
|
||||
wasFirst := cfg.CurrentProfile == ""
|
||||
if wasFirst {
|
||||
// The first profile is auto-selected; --use forces selection even when
|
||||
// another profile is already current.
|
||||
current := wasFirst || opts.Use
|
||||
if current {
|
||||
cfg.CurrentProfile = name
|
||||
}
|
||||
if err := config.Save(cfg); err != nil {
|
||||
@@ -141,12 +152,12 @@ func runAddWithConfig(opts *AddOptions, fopts *cmdutil.FormatOptions, name, host
|
||||
}
|
||||
|
||||
if fopts.WantsJSON() {
|
||||
return fopts.Emit(iostreams.IO.Out, addResult{Name: name, Host: host, User: opts.User, Current: wasFirst}, nil)
|
||||
return fopts.Emit(iostreams.IO.Out, addResult{Name: name, Host: host, User: opts.User, Current: current}, nil)
|
||||
}
|
||||
if wasFirst {
|
||||
fmt.Fprintf(iostreams.IO.Out, "✓ Added profile %s (now current). Run `weknora auth login --name %s` to attach credentials.\n", name, name)
|
||||
if current {
|
||||
fmt.Fprintf(iostreams.IO.Out, "✓ Added profile %s (now current). Run `weknora auth login` to attach credentials.\n", name)
|
||||
} else {
|
||||
fmt.Fprintf(iostreams.IO.Out, "✓ Added profile %s. Run `weknora auth login --name %s` to attach credentials.\n", name, name)
|
||||
fmt.Fprintf(iostreams.IO.Out, "✓ Added profile %s. Run `weknora profile use %s` then `weknora auth login` to attach credentials.\n", name, name)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -119,6 +119,44 @@ func TestAdd_SecondProfileDoesNotChangeCurrent(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestAdd_UseSwitchesCurrent asserts --use switches the current profile to the
|
||||
// newly-added one even when another profile is already current.
|
||||
func TestAdd_UseSwitchesCurrent(t *testing.T) {
|
||||
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
|
||||
cfg := &config.Config{
|
||||
CurrentProfile: "production",
|
||||
Profiles: map[string]config.Profile{"production": {Host: "https://prod.example.com"}},
|
||||
}
|
||||
if err := config.Save(cfg); err != nil {
|
||||
t.Fatalf("Save: %v", err)
|
||||
}
|
||||
|
||||
host, err := cmdutil.NormalizeHost("https://h")
|
||||
if err != nil {
|
||||
t.Fatalf("NormalizeHost: %v", err)
|
||||
}
|
||||
loaded, err := config.Load()
|
||||
if err != nil {
|
||||
t.Fatalf("Load: %v", err)
|
||||
}
|
||||
if err := runAddWithConfig(&AddOptions{Host: host, Use: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, "new", host, loaded); err != nil {
|
||||
t.Fatalf("runAddWithConfig: %v", err)
|
||||
}
|
||||
|
||||
got, _ := config.Load()
|
||||
if got.CurrentProfile != "new" {
|
||||
t.Errorf("--use must switch current to the new profile; got %q", got.CurrentProfile)
|
||||
}
|
||||
if _, ok := got.Profiles["new"]; !ok {
|
||||
t.Errorf("new profile not registered; keys=%v", profileKeys(got.Profiles))
|
||||
}
|
||||
if !strings.Contains(out.String(), "now current") {
|
||||
t.Errorf("output should note the profile is now current, got %q", out.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdd_JSON(t *testing.T) {
|
||||
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
|
||||
@@ -53,6 +53,11 @@ the CLI can talk to; "auth list" is the catalog of *how*.`,
|
||||
},
|
||||
}
|
||||
cmdutil.AddFormatFlag(cmd, profileListFields...)
|
||||
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
|
||||
UsedFor: "list configured connection profiles (name, host, which is active)",
|
||||
Examples: []string{"weknora profile list", "weknora profile list --jq '.data[].name'"},
|
||||
Output: "envelope.data is an array of {name, host, user, current}",
|
||||
})
|
||||
return cmd
|
||||
}
|
||||
|
||||
|
||||
@@ -117,7 +117,7 @@ func runRemove(opts *RemoveOptions, fopts *cmdutil.FormatOptions, name string, s
|
||||
// Confirmation only fires for removing the current profile - non-current
|
||||
// remove uses the same low-friction policy as `auth logout`.
|
||||
if wasCurrent {
|
||||
if err := cmdutil.ConfirmDestructive(p, opts.Yes, jsonOut, "current profile", name, "profile.remove", fmt.Sprintf("weknora profile remove %s -y", name)); err != nil {
|
||||
if err := cmdutil.ConfirmDestructive(p, opts.Yes, jsonOut, "remove", "current profile", name, "profile.remove", fmt.Sprintf("weknora profile remove %s -y", name)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,6 +17,7 @@ var profileUseFields = []string{"current_profile", "previous_profile"}
|
||||
|
||||
// NewCmdUse builds the `weknora profile use <name>` command.
|
||||
func NewCmdUse(f *cmdutil.Factory) *cobra.Command {
|
||||
var dryRun bool
|
||||
cmd := &cobra.Command{
|
||||
Use: "use <name>",
|
||||
Short: "Switch the default profile for subsequent commands",
|
||||
@@ -39,10 +40,23 @@ the global --profile flag instead, which writes nothing to disk.`,
|
||||
return err
|
||||
}
|
||||
fopts.ResolveDefault(iostreams.IO.IsStdoutTTY())
|
||||
if handled, err := cmdutil.HandleDryRun(c, dryRun, cmdutil.DryRunPlan{
|
||||
Action: "profile.use",
|
||||
Args: map[string]any{"name": args[0]},
|
||||
}); handled {
|
||||
return err
|
||||
}
|
||||
return runUse(args[0], fopts)
|
||||
},
|
||||
}
|
||||
cmdutil.AddFormatFlag(cmd, profileUseFields...)
|
||||
cmdutil.AddDryRunFlag(cmd, &dryRun)
|
||||
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
|
||||
UsedFor: "switch the default profile for subsequent commands (persists to config)",
|
||||
RequiredFlags: []string{"<name> (positional)"},
|
||||
Examples: []string{"weknora profile use staging"},
|
||||
Output: "envelope.data confirms the now-active profile",
|
||||
})
|
||||
return cmd
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user