diff --git a/cli/cmd/auth/list.go b/cli/cmd/auth/list.go index e4d3ce4e..8da60152 100644 --- a/cli/cmd/auth/list.go +++ b/cli/cmd/auth/list.go @@ -76,7 +76,7 @@ func runList(opts *ListOptions, f *cmdutil.Factory) error { if e.Current { marker = "* " } - fmt.Fprintf(tw, "%s%s\t%s\t%s\t%s\n", marker, e.Name, e.Host, dashIfEmpty(e.User), e.Mode) + fmt.Fprintf(tw, "%s%s\t%s\t%s\t%s\n", marker, e.Name, e.Host, format.DashIfEmpty(e.User), e.Mode) } return tw.Flush() } @@ -95,10 +95,3 @@ func inferMode(apiKeyRef, tokenRef string) string { return "unknown" } } - -func dashIfEmpty(s string) string { - if s == "" { - return "-" - } - return s -} diff --git a/cli/cmd/auth/login.go b/cli/cmd/auth/login.go index 6f99f068..976647bb 100644 --- a/cli/cmd/auth/login.go +++ b/cli/cmd/auth/login.go @@ -4,7 +4,6 @@ import ( "context" "fmt" "io" - "net/url" "strings" "github.com/spf13/cobra" @@ -217,14 +216,8 @@ func saveContextRef(opts *LoginOptions, f *cmdutil.Factory, ctx *config.Context, // 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 + _, err := cmdutil.NormalizeHost(host) + return err } // readStdinTrimmed reads all of r and returns the result with surrounding diff --git a/cli/cmd/context/add.go b/cli/cmd/context/add.go new file mode 100644 index 00000000..9b21e2b2 --- /dev/null +++ b/cli/cmd/context/add.go @@ -0,0 +1,150 @@ +package contextcmd + +import ( + "fmt" + "strings" + + "github.com/spf13/cobra" + + "github.com/Tencent/WeKnora/cli/internal/agent" + "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" +) + +// AddOptions captures `weknora context add` flag state. +type AddOptions struct { + Host string + User string + JSONOut bool +} + +// addResult is the typed payload emitted under data on success. +type addResult struct { + Name string `json:"name"` + Host string `json:"host"` + User string `json:"user,omitempty"` + Current bool `json:"current"` +} + +// NewCmdAdd builds `weknora context add`. Registers a *credentialless* +// connection target — host + optional user only. Credentials for the new +// context are attached separately with `weknora auth login --name `, +// reflecting gh's separation of "where" the CLI talks to (the host) and +// "how" it authenticates (the credential). kubectl's `config set-context` +// covers the same operation under a different surface convention. If you +// want one command for both, run `weknora auth login --name --host +// ` instead. +func NewCmdAdd(f *cmdutil.Factory) *cobra.Command { + opts := &AddOptions{} + cmd := &cobra.Command{ + Use: "add ", + Short: "Register a new context (host without credentials)", + Long: `Add a new context entry to config.yaml. Stores host (and optionally +user) but does NOT prompt for credentials. Use ` + "`weknora auth login --name `" + ` to +attach credentials in a single step instead, or run ` + "`weknora auth login --name `" + ` after +` + "`weknora context add`" + ` to fill them in. + +The first context added is auto-selected as the current context. Subsequent +adds leave the current context untouched.`, + Example: ` weknora context add staging --host https://staging.example.com + weknora context add prod --host https://prod.example.com --user alice@example.com`, + Args: cobra.ExactArgs(1), + RunE: func(c *cobra.Command, args []string) error { + return runAdd(opts, args[0]) + }, + } + 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 `context list` (optional, cosmetic only)") + cmd.Flags().BoolVar(&opts.JSONOut, "json", false, "Output JSON envelope") + _ = cmd.MarkFlagRequired("host") + agent.SetAgentHelp(cmd, "Adds a context. First context added auto-becomes current. Errors with resource.already_exists if name collides; input.invalid_argument if --host is not an absolute http(s) URL.") + return cmd +} + +func runAdd(opts *AddOptions, name string) error { + if err := validateName(name); err != nil { + return err + } + host, err := cmdutil.NormalizeHost(opts.Host) + if err != nil { + return err + } + + cfg, err := config.Load() + if err != nil { + return err + } + if _, exists := cfg.Contexts[name]; exists { + return &cmdutil.Error{ + Code: cmdutil.CodeResourceAlreadyExists, + Message: fmt.Sprintf("context %q already exists", name), + Hint: fmt.Sprintf("use a different name, or run `weknora context remove %s` first", name), + } + } + if cfg.Contexts == nil { + cfg.Contexts = map[string]config.Context{} + } + cfg.Contexts[name] = config.Context{Host: host, User: opts.User} + wasFirst := cfg.CurrentContext == "" + if wasFirst { + cfg.CurrentContext = name + } + if err := config.Save(cfg); err != nil { + return cmdutil.Wrapf(cmdutil.CodeLocalFileIO, err, "save config") + } + + risk := &format.Risk{Level: format.RiskWrite, Action: fmt.Sprintf("add context %s", name)} + if opts.JSONOut { + return format.WriteEnvelope(iostreams.IO.Out, format.SuccessWithRisk( + addResult{Name: name, Host: host, User: opts.User, Current: wasFirst}, + &format.Meta{Context: cfg.CurrentContext}, + risk, + )) + } + if wasFirst { + fmt.Fprintf(iostreams.IO.Out, "✓ Added context %s (now current). Run `weknora auth login --name %s` to attach credentials.\n", name, name) + } else { + fmt.Fprintf(iostreams.IO.Out, "✓ Added context %s. Run `weknora auth login --name %s` to attach credentials.\n", name, name) + } + return nil +} + +// validateName enforces the allowlist advertised in the --help hint: letters, +// digits, dash, underscore, dot. The `.` exception lets emails / DNS-like +// names through; the path-traversal `..` is structurally rejected by a +// separate guard because it would let a hand-edited config.yaml claim a +// context whose name walks out of the keyring namespace. +func validateName(name string) error { + if name == "" { + return &cmdutil.Error{ + Code: cmdutil.CodeInputInvalidArgument, + Message: "context name must not be empty", + } + } + if name == "." || name == ".." || strings.Contains(name, "/") || strings.Contains(name, "\\") { + return &cmdutil.Error{ + Code: cmdutil.CodeInputInvalidArgument, + Message: fmt.Sprintf("context name %q is reserved or path-like", name), + Hint: "use letters, digits, dashes, underscores, or dots", + } + } + for _, r := range name { + switch { + case r >= 'a' && r <= 'z', + r >= 'A' && r <= 'Z', + r >= '0' && r <= '9', + r == '-' || r == '_' || r == '.': + continue + default: + return &cmdutil.Error{ + Code: cmdutil.CodeInputInvalidArgument, + Message: fmt.Sprintf("context name %q contains invalid character %q", name, r), + Hint: "use letters, digits, dashes, underscores, or dots", + } + } + } + return nil +} + diff --git a/cli/cmd/context/add_test.go b/cli/cmd/context/add_test.go new file mode 100644 index 00000000..862557a1 --- /dev/null +++ b/cli/cmd/context/add_test.go @@ -0,0 +1,141 @@ +package contextcmd + +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/format" + "github.com/Tencent/WeKnora/cli/internal/iostreams" +) + +func TestAdd_HappyPath(t *testing.T) { + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + out, _ := iostreams.SetForTest(t) + + if err := runAdd(&AddOptions{Host: "https://my.example.com", User: "alice@example.com"}, "staging"); err != nil { + t.Fatalf("runAdd: %v", err) + } + + cfg, err := config.Load() + if err != nil { + t.Fatalf("Load: %v", err) + } + c, ok := cfg.Contexts["staging"] + if !ok { + t.Fatalf("staging not in Contexts; got keys=%v", contextKeys(cfg.Contexts)) + } + if c.Host != "https://my.example.com" { + t.Errorf("Host=%q, want https://my.example.com", c.Host) + } + if c.User != "alice@example.com" { + t.Errorf("User=%q, want alice@example.com", c.User) + } + // First context auto-becomes current. + if cfg.CurrentContext != "staging" { + t.Errorf("first context should auto-become current, got CurrentContext=%q", cfg.CurrentContext) + } + if !strings.Contains(out.String(), "staging") { + t.Errorf("output should mention added name, got %q", out.String()) + } +} + +func TestAdd_DuplicateName(t *testing.T) { + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + _, _ = iostreams.SetForTest(t) + + cfg := &config.Config{ + CurrentContext: "staging", + Contexts: map[string]config.Context{"staging": {Host: "https://old.example.com"}}, + } + if err := config.Save(cfg); err != nil { + t.Fatalf("Save: %v", err) + } + + err := runAdd(&AddOptions{Host: "https://new.example.com"}, "staging") + if err == nil { + t.Fatal("expected error on duplicate name") + } + cm, ok := err.(*cmdutil.Error) + if !ok { + t.Fatalf("expected *cmdutil.Error, got %T", err) + } + if cm.Code != cmdutil.CodeResourceAlreadyExists { + t.Errorf("code=%q, want %q", cm.Code, cmdutil.CodeResourceAlreadyExists) + } + // Existing entry must NOT be overwritten. + got, _ := config.Load() + if got.Contexts["staging"].Host != "https://old.example.com" { + t.Errorf("existing context overwritten; Host=%q", got.Contexts["staging"].Host) + } +} + +func TestAdd_BadHost(t *testing.T) { + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + _, _ = iostreams.SetForTest(t) + + bad := []string{ + "", // empty + "my.example.com", // missing scheme + "ftp://my.example.com", // wrong scheme + "http://", // missing host + } + for _, h := range bad { + err := runAdd(&AddOptions{Host: h}, "staging") + if err == nil { + t.Errorf("host=%q: expected error", h) + continue + } + cm, ok := err.(*cmdutil.Error) + if !ok { + t.Errorf("host=%q: expected *cmdutil.Error, got %T", h, err) + continue + } + if cm.Code != cmdutil.CodeInputInvalidArgument { + t.Errorf("host=%q: code=%q, want %q", h, cm.Code, cmdutil.CodeInputInvalidArgument) + } + } +} + +func TestAdd_SecondContextDoesNotChangeCurrent(t *testing.T) { + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + _, _ = iostreams.SetForTest(t) + + cfg := &config.Config{ + CurrentContext: "production", + Contexts: map[string]config.Context{"production": {Host: "https://prod.example.com"}}, + } + if err := config.Save(cfg); err != nil { + t.Fatalf("Save: %v", err) + } + + if err := runAdd(&AddOptions{Host: "https://stg.example.com"}, "staging"); err != nil { + t.Fatalf("runAdd: %v", err) + } + got, _ := config.Load() + if got.CurrentContext != "production" { + t.Errorf("adding a second context must not switch current; got %q", got.CurrentContext) + } +} + +func TestAdd_JSON(t *testing.T) { + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + out, _ := iostreams.SetForTest(t) + + if err := runAdd(&AddOptions{Host: "https://my.example.com", JSONOut: true}, "staging"); err != nil { + t.Fatalf("runAdd: %v", err) + } + var env format.Envelope + if err := json.Unmarshal(out.Bytes(), &env); err != nil { + t.Fatalf("invalid JSON envelope: %v\noutput=%q", err, out.String()) + } + if !env.OK { + t.Fatalf("envelope.ok=false, error=%+v", env.Error) + } + if env.Risk == nil || env.Risk.Level != format.RiskWrite { + t.Errorf("envelope.risk should be write-level, got %+v", env.Risk) + } +} + diff --git a/cli/cmd/context/context.go b/cli/cmd/context/context.go index f2b23876..23c36004 100644 --- a/cli/cmd/context/context.go +++ b/cli/cmd/context/context.go @@ -1,5 +1,9 @@ -// Package contextcmd holds `weknora context` command tree (use; list / set / -// delete in v0.4). +// Package contextcmd holds `weknora context` command tree +// (list / add / remove / use). Uses the gh-style ` ` shape +// consistent with the rest of this CLI. kubectl exposes the same set +// of operations as flat hyphenated subcommands (`config get-contexts / +// set-context / delete-context / use-context`) — a different idiom we +// don't adopt because it would make `context` an outlier in our tree. // // Package name `contextcmd` (not `context`) to avoid shadowing stdlib context. // The cobra Use: string is "context" — this is what users type. @@ -19,6 +23,9 @@ func NewCmd(f *cmdutil.Factory) *cobra.Command { Args: cobra.NoArgs, Run: func(c *cobra.Command, _ []string) { _ = c.Help() }, } + cmd.AddCommand(NewCmdList(f)) + cmd.AddCommand(NewCmdAdd(f)) + cmd.AddCommand(NewCmdRemove(f)) cmd.AddCommand(NewCmdUse(f)) return cmd } diff --git a/cli/cmd/context/list.go b/cli/cmd/context/list.go new file mode 100644 index 00000000..74f13542 --- /dev/null +++ b/cli/cmd/context/list.go @@ -0,0 +1,91 @@ +package contextcmd + +import ( + "fmt" + "sort" + "text/tabwriter" + + "github.com/spf13/cobra" + + "github.com/Tencent/WeKnora/cli/internal/agent" + "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" +) + +// ListOptions captures `weknora context list` flag state. +type ListOptions struct { + JSONOut bool +} + +// listEntry is one row in the rendered table / one element of envelope.data. +type listEntry struct { + Name string `json:"name"` + Host string `json:"host"` + User string `json:"user,omitempty"` + Current bool `json:"current"` +} + +// NewCmdList builds `weknora context list`. Same listing shape as gh +// `auth status` (per-host enumeration with an active marker). The kubectl +// equivalent is `config get-contexts` — same data, different surface +// convention (kubectl uses hyphenated subcommands; we use noun-verb). +// Reads only config.yaml — no network, no keyring touch. +func NewCmdList(f *cmdutil.Factory) *cobra.Command { + opts := &ListOptions{} + cmd := &cobra.Command{ + Use: "list", + Short: "List configured contexts", + Long: `Show every context registered in ~/.config/weknora/config.yaml. The +active context (used by subsequent commands when --context is unset) is +marked with a leading "*". No network requests are issued. + +The credential mode (api-key vs password) is intentionally not shown here — +run "weknora auth list" for that. "context list" is the catalog of *where* +the CLI can talk to; "auth list" is the catalog of *how*.`, + Args: cobra.NoArgs, + RunE: func(c *cobra.Command, _ []string) error { + return runList(opts) + }, + } + cmd.Flags().BoolVar(&opts.JSONOut, "json", false, "Output JSON envelope") + agent.SetAgentHelp(cmd, "Lists CLI contexts (name/host/user/current). Read-only, no network. Use this before context use to verify the target name exists.") + return cmd +} + +func runList(opts *ListOptions) error { + cfg, err := config.Load() + if err != nil { + return err + } + entries := make([]listEntry, 0, len(cfg.Contexts)) + for name, c := range cfg.Contexts { + entries = append(entries, listEntry{ + Name: name, + Host: c.Host, + User: c.User, + Current: name == cfg.CurrentContext, + }) + } + sort.Slice(entries, func(i, j int) bool { return entries[i].Name < entries[j].Name }) + + if opts.JSONOut { + return format.WriteEnvelope(iostreams.IO.Out, + format.Success(entries, &format.Meta{Context: cfg.CurrentContext})) + } + if len(entries) == 0 { + fmt.Fprintln(iostreams.IO.Out, "No contexts configured. Run `weknora auth login` (or `weknora context add`) to create one.") + return nil + } + tw := tabwriter.NewWriter(iostreams.IO.Out, 0, 0, 2, ' ', 0) + fmt.Fprintln(tw, " NAME\tHOST\tUSER") + for _, e := range entries { + marker := " " + if e.Current { + marker = "* " + } + fmt.Fprintf(tw, "%s%s\t%s\t%s\n", marker, e.Name, e.Host, format.DashIfEmpty(e.User)) + } + return tw.Flush() +} diff --git a/cli/cmd/context/list_test.go b/cli/cmd/context/list_test.go new file mode 100644 index 00000000..8a057d31 --- /dev/null +++ b/cli/cmd/context/list_test.go @@ -0,0 +1,119 @@ +package contextcmd + +import ( + "encoding/json" + "strings" + "testing" + + "github.com/Tencent/WeKnora/cli/internal/config" + "github.com/Tencent/WeKnora/cli/internal/format" + "github.com/Tencent/WeKnora/cli/internal/iostreams" +) + +func TestList_Empty(t *testing.T) { + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + out, _ := iostreams.SetForTest(t) + + if err := runList(&ListOptions{}); err != nil { + t.Fatalf("runList: %v", err) + } + if !strings.Contains(out.String(), "No contexts") { + t.Errorf("empty output should mention `No contexts`, got %q", out.String()) + } +} + +func TestList_MultipleSorted(t *testing.T) { + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + out, _ := iostreams.SetForTest(t) + + cfg := &config.Config{ + CurrentContext: "staging", + Contexts: map[string]config.Context{ + "production": {Host: "https://prod.example.com", User: "alice@example.com"}, + "staging": {Host: "https://staging.example.com"}, + "alpha": {Host: "https://alpha.example.com"}, + }, + } + if err := config.Save(cfg); err != nil { + t.Fatalf("Save: %v", err) + } + + if err := runList(&ListOptions{}); err != nil { + t.Fatalf("runList: %v", err) + } + got := out.String() + // header + if !strings.Contains(got, "NAME") || !strings.Contains(got, "HOST") { + t.Errorf("missing header NAME/HOST in %q", got) + } + // row ordering: alpha < production < staging + iAlpha := strings.Index(got, "alpha") + iProd := strings.Index(got, "production") + iStg := strings.Index(got, "staging") + if !(iAlpha < iProd && iProd < iStg) { + t.Errorf("rows must be alphabetical, got order alpha=%d prod=%d staging=%d in %q", iAlpha, iProd, iStg, got) + } + // active marker on staging row + stgLine := lineContaining(got, "staging") + if !strings.HasPrefix(stgLine, "*") { + t.Errorf("active context row must start with `*`, got %q", stgLine) + } +} + +func TestList_JSON(t *testing.T) { + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + out, _ := iostreams.SetForTest(t) + + cfg := &config.Config{ + CurrentContext: "staging", + Contexts: map[string]config.Context{ + "staging": {Host: "https://staging.example.com", User: "bob@example.com"}, + "production": {Host: "https://prod.example.com"}, + }, + } + if err := config.Save(cfg); err != nil { + t.Fatalf("Save: %v", err) + } + + if err := runList(&ListOptions{JSONOut: true}); err != nil { + t.Fatalf("runList: %v", err) + } + + var env format.Envelope + if err := json.Unmarshal(out.Bytes(), &env); err != nil { + t.Fatalf("invalid JSON envelope: %v\noutput=%q", err, out.String()) + } + if !env.OK { + t.Fatalf("envelope.ok=false, error=%+v", env.Error) + } + if env.Meta == nil || env.Meta.Context != "staging" { + t.Errorf("envelope._meta.context should be %q, got %+v", "staging", env.Meta) + } + rows, ok := env.Data.([]any) + if !ok { + t.Fatalf("envelope.data should be []listEntry, got %T", env.Data) + } + if len(rows) != 2 { + t.Fatalf("expected 2 entries, got %d", len(rows)) + } + // alphabetical: production before staging + first := rows[0].(map[string]any) + if first["name"] != "production" { + t.Errorf("first row should be production, got %v", first) + } + second := rows[1].(map[string]any) + if second["name"] != "staging" || second["current"] != true { + t.Errorf("second row should be staging with current=true, got %v", second) + } +} + +// lineContaining returns the first line of s that contains needle (trimmed of +// the trailing newline) or "" if no line matches. +func lineContaining(s, needle string) string { + for l := range strings.SplitSeq(s, "\n") { + if strings.Contains(l, needle) { + return l + } + } + return "" +} diff --git a/cli/cmd/context/remove.go b/cli/cmd/context/remove.go new file mode 100644 index 00000000..eba5b3b9 --- /dev/null +++ b/cli/cmd/context/remove.go @@ -0,0 +1,148 @@ +package contextcmd + +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/config" + "github.com/Tencent/WeKnora/cli/internal/format" + "github.com/Tencent/WeKnora/cli/internal/iostreams" + "github.com/Tencent/WeKnora/cli/internal/prompt" + "github.com/Tencent/WeKnora/cli/internal/secrets" +) + +// RemoveOptions captures `weknora context remove` flag state. Yes is sourced +// from the global -y/--yes persistent flag (matches `kb delete`). +type RemoveOptions struct { + Yes bool + JSONOut bool + DryRun bool +} + +// removeResult is the typed payload emitted under data on success. +type removeResult struct { + Name string `json:"name"` + Removed bool `json:"removed"` + WasCurrent bool `json:"was_current"` +} + +// NewCmdRemove builds `weknora context remove`. Drops the entry from +// config.yaml and best-effort clears keyring references. The kubectl +// equivalent is `config delete-context`; we use the noun-verb form +// instead. Removing a non-current context is low-friction (no prompt). +// Removing the *current* context triggers the lark-cli exit-10 +// confirmation protocol because subsequent commands will have no +// default connection target. +func NewCmdRemove(f *cmdutil.Factory) *cobra.Command { + opts := &RemoveOptions{} + cmd := &cobra.Command{ + Use: "remove ", + Short: "Remove a context (drops entry, clears keyring refs)", + Long: `Deletes the named context from config.yaml and best-effort clears any +keyring references it owned (matches ` + "`weknora auth logout`" + `). + +Removing the current context also clears CurrentContext — subsequent commands +will error until you select another with ` + "`weknora context use `" + ` or pick +one up via the global ` + "`--context`" + ` flag. Because that change is observable in +every later command, removing the current context requires explicit -y/--yes +in scripted / --json invocations (exit-10 protocol; AGENTS.md).`, + Example: ` weknora context remove staging # remove non-current → no prompt + weknora context remove production -y # remove current → confirm`, + Args: cobra.ExactArgs(1), + RunE: func(c *cobra.Command, args []string) error { + opts.Yes, _ = c.Flags().GetBool("yes") + opts.DryRun = cmdutil.IsDryRun(c) + store, err := f.Secrets() + if err != nil { + return err + } + return runRemove(opts, args[0], store, f.Prompter()) + }, + } + cmd.Flags().BoolVar(&opts.JSONOut, "json", false, "Output JSON envelope") + agent.SetAgentHelp(cmd, "Removes a context entry. Removing the current context requires -y in non-TTY/--json (exit-10). Always best-effort clears keyring refs.") + return cmd +} + +func runRemove(opts *RemoveOptions, name string, store secrets.Store, p prompt.Prompter) error { + cfg, err := config.Load() + if err != nil { + return err + } + ctx, exists := cfg.Contexts[name] + if !exists { + return notFoundError(name, cfg) + } + wasCurrent := name == cfg.CurrentContext + risk := riskForRemove(name, wasCurrent) + + if opts.DryRun { + return cmdutil.EmitDryRun(opts.JSONOut, + removeResult{Name: name, Removed: false, WasCurrent: wasCurrent}, + &format.Meta{Context: cfg.CurrentContext}, + risk) + } + // Confirmation only fires for removing the current context — non-current + // remove matches `auth logout`'s low-friction policy. + if wasCurrent { + if err := cmdutil.ConfirmDestructive(p, opts.Yes, opts.JSONOut, "current context", name); err != nil { + return err + } + } + + // Config first, secrets after: a crash in between leaves an orphan + // keyring entry but no dangling config ref (same ordering as auth logout). + delete(cfg.Contexts, name) + if wasCurrent { + cfg.CurrentContext = "" + } + if err := config.Save(cfg); err != nil { + return cmdutil.Wrapf(cmdutil.CodeLocalFileIO, err, "save config") + } + clearContextSecrets(store, ctx, name) + + result := removeResult{Name: name, Removed: true, WasCurrent: wasCurrent} + if opts.JSONOut { + return format.WriteEnvelope(iostreams.IO.Out, format.SuccessWithRisk( + result, &format.Meta{Context: cfg.CurrentContext}, risk, + )) + } + if wasCurrent { + fmt.Fprintf(iostreams.IO.Out, "✓ Removed context %s (current context cleared — run `weknora context use ` to pick another)\n", name) + } else { + fmt.Fprintf(iostreams.IO.Out, "✓ Removed context %s\n", name) + } + return nil +} + +// riskForRemove returns the operation risk: high-risk-write only when the +// target is the currently-active context (subsequent commands will have no +// default --context until the user picks one). +func riskForRemove(name string, wasCurrent bool) *format.Risk { + if wasCurrent { + return &format.Risk{ + Level: format.RiskHighRiskWrite, + Action: fmt.Sprintf("remove context %s (the current context — subsequent commands will need a new --context)", name), + } + } + return &format.Risk{Level: format.RiskWrite, Action: fmt.Sprintf("remove context %s", name)} +} + +// clearContextSecrets mirrors auth/logout.go: best-effort delete every secret +// slot the context references. Errors are swallowed so a missing keyring +// entry doesn't block remove (logout had the same policy from v0.2). +func clearContextSecrets(store secrets.Store, c config.Context, name string) { + if c.TokenRef != "" { + _ = store.Delete(name, "access") + } + if c.RefreshRef != "" { + _ = store.Delete(name, "refresh") + } + if c.APIKeyRef != "" { + _ = store.Delete(name, "api_key") + } +} + diff --git a/cli/cmd/context/remove_test.go b/cli/cmd/context/remove_test.go new file mode 100644 index 00000000..7de7a3bb --- /dev/null +++ b/cli/cmd/context/remove_test.go @@ -0,0 +1,258 @@ +package contextcmd + +import ( + "encoding/json" + "errors" + "strings" + "testing" + + "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" + "github.com/Tencent/WeKnora/cli/internal/prompt" + "github.com/Tencent/WeKnora/cli/internal/secrets" +) + +// confirmPrompter scripts a Confirm answer; Input/Password unused. +type confirmPrompter struct { + answer bool + err error + asked bool +} + +func (c *confirmPrompter) Input(string, string) (string, error) { + return "", prompt.ErrAgentNoPrompt +} +func (c *confirmPrompter) Password(string) (string, error) { return "", prompt.ErrAgentNoPrompt } +func (c *confirmPrompter) Confirm(string, bool) (bool, error) { + c.asked = true + return c.answer, c.err +} + +// seedStore returns a MemStore pre-loaded with sentinel values for every +// secret slot a context might reference. Tests assert deletion by checking +// `secrets.ErrNotFound` post-runRemove. +func seedStore(t *testing.T, name string, slots ...string) *secrets.MemStore { + t.Helper() + s := secrets.NewMemStore() + for _, slot := range slots { + if err := s.Set(name, slot, "sentinel-"+name+"-"+slot); err != nil { + t.Fatalf("seed %s/%s: %v", name, slot, err) + } + } + return s +} + +func assertDeleted(t *testing.T, s *secrets.MemStore, name, slot string) { + t.Helper() + if _, err := s.Get(name, slot); !errors.Is(err, secrets.ErrNotFound) { + t.Errorf("expected %s/%s removed, got err=%v", name, slot, err) + } +} + +func TestRemove_NonCurrent_NoPromptNeeded(t *testing.T) { + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + out, _ := iostreams.SetForTest(t) + + cfg := &config.Config{ + CurrentContext: "production", + Contexts: map[string]config.Context{ + "production": {Host: "https://prod.example.com", TokenRef: "mem://production/access"}, + "staging": {Host: "https://staging.example.com", APIKeyRef: "mem://staging/api_key"}, + }, + } + if err := config.Save(cfg); err != nil { + t.Fatalf("Save: %v", err) + } + + store := seedStore(t, "staging", "api_key") + p := &confirmPrompter{} + if err := runRemove(&RemoveOptions{}, "staging", store, p); err != nil { + t.Fatalf("runRemove: %v", err) + } + if p.asked { + t.Errorf("non-current remove must not prompt") + } + + got, _ := config.Load() + if _, exists := got.Contexts["staging"]; exists { + t.Errorf("staging should have been removed; Contexts=%v", got.Contexts) + } + if got.CurrentContext != "production" { + t.Errorf("CurrentContext must be unchanged, got %q", got.CurrentContext) + } + assertDeleted(t, store, "staging", "api_key") + if !strings.Contains(out.String(), "staging") { + t.Errorf("output should mention removed context, got %q", out.String()) + } +} + +func TestRemove_NotFound_WithDidYouMean(t *testing.T) { + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + _, _ = iostreams.SetForTest(t) + + cfg := &config.Config{Contexts: map[string]config.Context{ + "production": {Host: "https://prod"}, + "staging": {Host: "https://staging"}, + }} + if err := config.Save(cfg); err != nil { + t.Fatalf("Save: %v", err) + } + + err := runRemove(&RemoveOptions{}, "prodution", secrets.NewMemStore(), &confirmPrompter{}) + if err == nil { + t.Fatal("expected not-found error") + } + cm, ok := err.(*cmdutil.Error) + if !ok { + t.Fatalf("expected *cmdutil.Error, got %T", err) + } + if cm.Code != cmdutil.CodeLocalContextNotFound { + t.Errorf("code=%q, want %q", cm.Code, cmdutil.CodeLocalContextNotFound) + } + if !strings.Contains(cm.Hint, "production") { + t.Errorf("hint should suggest 'production', got %q", cm.Hint) + } +} + +func TestRemove_Current_NonTTY_NoYes_RequiresConfirmation(t *testing.T) { + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + _, _ = iostreams.SetForTest(t) + + cfg := &config.Config{ + CurrentContext: "production", + Contexts: map[string]config.Context{ + "production": {Host: "https://prod", TokenRef: "mem://production/access"}, + "staging": {Host: "https://staging"}, + }, + } + if err := config.Save(cfg); err != nil { + t.Fatalf("Save: %v", err) + } + + store := seedStore(t, "production", "access") + err := runRemove(&RemoveOptions{}, "production", store, &confirmPrompter{}) + if err == nil { + t.Fatal("expected confirmation-required error") + } + cm, ok := err.(*cmdutil.Error) + if !ok { + t.Fatalf("expected *cmdutil.Error, got %T", err) + } + if cm.Code != cmdutil.CodeInputConfirmationRequired { + t.Errorf("code=%q, want %q", cm.Code, cmdutil.CodeInputConfirmationRequired) + } + if cmdutil.ExitCode(err) != 10 { + t.Errorf("expected exit-10, got %d", cmdutil.ExitCode(err)) + } + // Must not have mutated config or keyring. + if got, _ := config.Load(); got.CurrentContext != "production" { + t.Errorf("config mutated despite confirmation gate: CurrentContext=%q", got.CurrentContext) + } + if v, err := store.Get("production", "access"); err != nil || v == "" { + t.Errorf("keyring touched before confirmation, get=%q err=%v", v, err) + } +} + +func TestRemove_Current_WithYes_ClearsCurrent(t *testing.T) { + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + out, _ := iostreams.SetForTest(t) + + cfg := &config.Config{ + CurrentContext: "production", + Contexts: map[string]config.Context{ + "production": {Host: "https://prod", TokenRef: "mem://production/access"}, + "staging": {Host: "https://staging"}, + }, + } + if err := config.Save(cfg); err != nil { + t.Fatalf("Save: %v", err) + } + + store := seedStore(t, "production", "access") + if err := runRemove(&RemoveOptions{Yes: true}, "production", store, &confirmPrompter{}); err != nil { + t.Fatalf("runRemove: %v", err) + } + got, _ := config.Load() + if _, exists := got.Contexts["production"]; exists { + t.Errorf("production should be removed") + } + if got.CurrentContext != "" { + t.Errorf("removing current must clear CurrentContext, got %q", got.CurrentContext) + } + assertDeleted(t, store, "production", "access") + if !strings.Contains(out.String(), "current context cleared") { + t.Errorf("output should warn about cleared current, got %q", out.String()) + } +} + +func TestRemove_Current_TTY_PromptNo(t *testing.T) { + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + _, errBuf := iostreams.SetForTestWithTTY(t) + + cfg := &config.Config{ + CurrentContext: "production", + Contexts: map[string]config.Context{"production": {Host: "https://prod"}}, + } + if err := config.Save(cfg); err != nil { + t.Fatalf("Save: %v", err) + } + + p := &confirmPrompter{answer: false} + err := runRemove(&RemoveOptions{}, "production", secrets.NewMemStore(), p) + if err == nil { + t.Fatal("expected user-aborted error") + } + cm, ok := err.(*cmdutil.Error) + if !ok { + t.Fatalf("expected *cmdutil.Error, got %T", err) + } + if cm.Code != cmdutil.CodeUserAborted { + t.Errorf("code=%q, want %q", cm.Code, cmdutil.CodeUserAborted) + } + if !p.asked { + t.Errorf("prompt should have been asked on TTY") + } + if !strings.Contains(errBuf.String(), "Aborted") { + t.Errorf("stderr should contain Aborted, got %q", errBuf.String()) + } + if got, _ := config.Load(); got.CurrentContext != "production" { + t.Errorf("aborted remove must not mutate config") + } +} + +func TestRemove_DryRun(t *testing.T) { + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + out, _ := iostreams.SetForTest(t) + + cfg := &config.Config{ + CurrentContext: "production", + Contexts: map[string]config.Context{"production": {Host: "https://prod", TokenRef: "mem://production/access"}}, + } + if err := config.Save(cfg); err != nil { + t.Fatalf("Save: %v", err) + } + + store := seedStore(t, "production", "access") + if err := runRemove(&RemoveOptions{DryRun: true, JSONOut: true}, "production", store, &confirmPrompter{}); err != nil { + t.Fatalf("runRemove dry-run: %v", err) + } + var env format.Envelope + if jerr := json.Unmarshal(out.Bytes(), &env); jerr != nil { + t.Fatalf("invalid envelope: %v\noutput=%q", jerr, out.String()) + } + if !env.OK || !env.DryRun { + t.Errorf("envelope should be ok=true, dry_run=true, got %+v", env) + } + if env.Risk == nil || env.Risk.Level != format.RiskHighRiskWrite { + t.Errorf("dry-run on current context should report high-risk-write, got %+v", env.Risk) + } + // Nothing actually mutated. + if got, _ := config.Load(); got.CurrentContext != "production" { + t.Errorf("dry-run must not mutate config") + } + if v, err := store.Get("production", "access"); err != nil || v == "" { + t.Errorf("dry-run must not touch keyring; get=%q err=%v", v, err) + } +} diff --git a/cli/internal/cmdutil/host.go b/cli/internal/cmdutil/host.go new file mode 100644 index 00000000..a212a26d --- /dev/null +++ b/cli/internal/cmdutil/host.go @@ -0,0 +1,39 @@ +package cmdutil + +import ( + "fmt" + "net/url" + "strings" +) + +// NormalizeHost validates and canonicalizes a `--host` / `--hostname` value. +// The returned string is trimmed of trailing slashes. Returns a typed +// CLI error (CodeInputMissingFlag for empty, CodeInputInvalidArgument for +// malformed) so callers can `return cmdutil.NormalizeHost(...)` directly. +// +// Rules (matches gh CLI's URL handling): +// - non-empty +// - scheme is http or https +// - URL parses +// - u.Host is non-empty (rejects "http://" which url.Parse accepts) +func NormalizeHost(host string) (string, error) { + host = strings.TrimRight(strings.TrimSpace(host), "/") + if host == "" { + return "", NewError(CodeInputInvalidArgument, "--host must not be empty") + } + u, err := url.Parse(host) + if err != nil { + return "", NewError(CodeInputInvalidArgument, fmt.Sprintf("--host %q is not a valid URL: %v", host, err)) + } + if u.Scheme != "http" && u.Scheme != "https" { + return "", &Error{ + Code: CodeInputInvalidArgument, + Message: fmt.Sprintf("--host scheme must be http or https, got %q", u.Scheme), + Hint: "example: https://kb.example.com", + } + } + if u.Host == "" { + return "", NewError(CodeInputInvalidArgument, fmt.Sprintf("--host %q is missing the host portion", host)) + } + return host, nil +} diff --git a/cli/internal/format/dash.go b/cli/internal/format/dash.go new file mode 100644 index 00000000..89c7faef --- /dev/null +++ b/cli/internal/format/dash.go @@ -0,0 +1,11 @@ +package format + +// DashIfEmpty returns "-" for empty strings, otherwise s itself. Standard +// rendering convention for human-readable table cells whose value is +// optional (e.g. user email in `auth list` / `context list`). +func DashIfEmpty(s string) string { + if s == "" { + return "-" + } + return s +}