1package command
2
3import (
4	"fmt"
5	"strings"
6
7	"github.com/hashicorp/vault/api"
8	"github.com/hashicorp/vault/sdk/helper/consts"
9	"github.com/mitchellh/cli"
10	"github.com/posener/complete"
11)
12
13var _ cli.Command = (*PluginDeregisterCommand)(nil)
14var _ cli.CommandAutocomplete = (*PluginDeregisterCommand)(nil)
15
16type PluginDeregisterCommand struct {
17	*BaseCommand
18}
19
20func (c *PluginDeregisterCommand) Synopsis() string {
21	return "Deregister an existing plugin in the catalog"
22}
23
24func (c *PluginDeregisterCommand) Help() string {
25	helpText := `
26Usage: vault plugin deregister [options] TYPE NAME
27
28  Deregister an existing plugin in the catalog. If the plugin does not exist,
29  no action is taken (the command is idempotent). The argument of type
30  takes "auth", "database", or "secret".
31
32  Deregister the plugin named my-custom-plugin:
33
34      $ vault plugin deregister auth my-custom-plugin
35
36` + c.Flags().Help()
37
38	return strings.TrimSpace(helpText)
39}
40
41func (c *PluginDeregisterCommand) Flags() *FlagSets {
42	return c.flagSet(FlagSetHTTP)
43}
44
45func (c *PluginDeregisterCommand) AutocompleteArgs() complete.Predictor {
46	return c.PredictVaultPlugins(consts.PluginTypeUnknown)
47}
48
49func (c *PluginDeregisterCommand) AutocompleteFlags() complete.Flags {
50	return c.Flags().Completions()
51}
52
53func (c *PluginDeregisterCommand) Run(args []string) int {
54	f := c.Flags()
55
56	if err := f.Parse(args); err != nil {
57		c.UI.Error(err.Error())
58		return 1
59	}
60
61	var pluginNameRaw, pluginTypeRaw string
62	args = f.Args()
63	switch {
64	case len(args) < 1:
65		c.UI.Error(fmt.Sprintf("Not enough arguments (expected 1 or 2, got %d)", len(args)))
66		return 1
67	case len(args) > 2:
68		c.UI.Error(fmt.Sprintf("Too many arguments (expected 1 or 2, got %d)", len(args)))
69		return 1
70
71	// These cases should come after invalid cases have been checked
72	case len(args) == 1:
73		pluginTypeRaw = "unknown"
74		pluginNameRaw = args[0]
75	case len(args) == 2:
76		pluginTypeRaw = args[0]
77		pluginNameRaw = args[1]
78	}
79
80	client, err := c.Client()
81	if err != nil {
82		c.UI.Error(err.Error())
83		return 2
84	}
85
86	pluginType, err := consts.ParsePluginType(strings.TrimSpace(pluginTypeRaw))
87	if err != nil {
88		c.UI.Error(err.Error())
89		return 2
90	}
91	pluginName := strings.TrimSpace(pluginNameRaw)
92
93	if err := client.Sys().DeregisterPlugin(&api.DeregisterPluginInput{
94		Name: pluginName,
95		Type: pluginType,
96	}); err != nil {
97		c.UI.Error(fmt.Sprintf("Error deregistering plugin named %s: %s", pluginName, err))
98		return 2
99	}
100
101	c.UI.Output(fmt.Sprintf("Success! Deregistered plugin (if it was registered): %s", pluginName))
102	return 0
103}
104