forked from spiffe/spire
/
set.go
96 lines (81 loc) · 2.64 KB
/
set.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package bundle
import (
"context"
"errors"
"flag"
"fmt"
"github.com/accuknox/spire/cmd/spire-server/util"
common_cli "github.com/accuknox/spire/pkg/common/cli"
"github.com/accuknox/spire/pkg/common/cliprinter"
"github.com/mitchellh/cli"
bundlev1 "github.com/spiffe/spire-api-sdk/proto/spire/api/server/bundle/v1"
"github.com/spiffe/spire-api-sdk/proto/spire/api/types"
"google.golang.org/grpc/codes"
)
// NewSetCommand creates a new "set" subcommand for "bundle" command.
func NewSetCommand() cli.Command {
return newSetCommand(common_cli.DefaultEnv)
}
func newSetCommand(env *common_cli.Env) cli.Command {
return util.AdaptCommand(env, &setCommand{env: env})
}
type setCommand struct {
env *common_cli.Env
// SPIFFE ID of the trust bundle
id string
// Path to the bundle on disk (optional). If empty, reads from stdin.
path string
bundleFormat string
printer cliprinter.Printer
}
func (c *setCommand) Name() string {
return "bundle set"
}
func (c *setCommand) Synopsis() string {
return "Creates or updates bundle data"
}
func (c *setCommand) AppendFlags(fs *flag.FlagSet) {
fs.StringVar(&c.id, "id", "", "SPIFFE ID of the trust domain")
fs.StringVar(&c.path, "path", "", "Path to the bundle data")
fs.StringVar(&c.bundleFormat, "format", util.FormatPEM, fmt.Sprintf("The format of the bundle data. Either %q or %q.", util.FormatPEM, util.FormatSPIFFE))
cliprinter.AppendFlagWithCustomPretty(&c.printer, fs, c.env, prettyPrintSet)
}
func (c *setCommand) Run(ctx context.Context, env *common_cli.Env, serverClient util.ServerClient) error {
if c.id == "" {
return errors.New("id flag is required")
}
bundleFormat, err := validateFormat(c.bundleFormat)
if err != nil {
return err
}
bundleBytes, err := loadParamData(env.Stdin, c.path)
if err != nil {
return fmt.Errorf("unable to load bundle data: %w", err)
}
bundle, err := util.ParseBundle(bundleBytes, bundleFormat, c.id)
if err != nil {
return err
}
bundleClient := serverClient.NewBundleClient()
resp, err := bundleClient.BatchSetFederatedBundle(ctx, &bundlev1.BatchSetFederatedBundleRequest{
Bundle: []*types.Bundle{bundle},
})
if err != nil {
return fmt.Errorf("failed to set federated bundle: %w", err)
}
return c.printer.PrintProto(resp)
}
func prettyPrintSet(env *common_cli.Env, results ...interface{}) error {
setResp, ok := results[0].(*bundlev1.BatchSetFederatedBundleResponse)
if !ok {
return cliprinter.ErrInternalCustomPrettyFunc
}
result := setResp.Results[0]
switch result.Status.Code {
case int32(codes.OK):
env.Println("bundle set.")
return nil
default:
return fmt.Errorf("failed to set federated bundle: %s", result.Status.Message)
}
}