| 1 | // Copyright The Notary Project Authors. |
| 2 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 3 | // you may not use this file except in compliance with the License. |
| 4 | // You may obtain a copy of the License at |
| 5 | // |
| 6 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 7 | // |
| 8 | // Unless required by applicable law or agreed to in writing, software |
| 9 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 11 | // See the License for the specific language governing permissions and |
| 12 | // limitations under the License. |
| 13 | |
| 14 | // Package cli provides boilerplate code required to generate plugin executable. |
| 15 | // At high level it performs following tasks |
| 16 | // 1. Validate command arguments |
| 17 | // 2. Read and unmarshal input |
| 18 | // 3. Execute relevant plugin functions |
| 19 | // 4. marshals output |
| 20 | package cli |
| 21 | |
| 22 | import ( |
| 23 | "context" |
| 24 | "encoding/json" |
| 25 | "errors" |
| 26 | "fmt" |
| 27 | "os" |
| 28 | "reflect" |
| 29 | |
| 30 | "github.com/notaryproject/notation-plugin-framework-go/internal/slices" |
| 31 | "github.com/notaryproject/notation-plugin-framework-go/log" |
| 32 | "github.com/notaryproject/notation-plugin-framework-go/plugin" |
| 33 | ) |
| 34 | |
| 35 | // CLI struct is used to create an executable for plugin. |
| 36 | type CLI struct { |
| 37 | pl plugin.Plugin |
| 38 | logger log.Logger |
| 39 | } |
| 40 | |
| 41 | // New creates a new CLI using given plugin |
| 42 | func New(pl plugin.Plugin) (*CLI, error) { |
| 43 | return NewWithLogger(pl, &discardLogger{}) |
| 44 | } |
| 45 | |
| 46 | // NewWithLogger creates a new CLI using given plugin and logger |
| 47 | func NewWithLogger(pl plugin.Plugin, l log.Logger) (*CLI, error) { |
| 48 | if pl == nil { |
| 49 | return nil, errors.New("plugin cannot be nil") |
| 50 | } |
| 51 | |
| 52 | return &CLI{ |
| 53 | pl: pl, |
| 54 | logger: l, |
| 55 | }, nil |
| 56 | } |
| 57 | |
| 58 | // Execute is main controller that reads/validates commands, parses input, executes relevant plugin functions |
| 59 | // and returns corresponding output. |
| 60 | func (c *CLI) Execute(ctx context.Context, args []string) { |
| 61 | c.validateArgs(ctx, args) |
| 62 | |
| 63 | rescueStdOut := deferStdout() |
| 64 | command := args[1] |
| 65 | var resp any |
| 66 | var err error |
| 67 | switch plugin.Command(command) { |
| 68 | case plugin.CommandGetMetadata: |
| 69 | var request plugin.GetMetadataRequest |
| 70 | err = c.unmarshalRequest(&request) |
| 71 | if err == nil { |
| 72 | c.logger.Debugf("executing %s plugin's GetMetadata function", reflect.TypeOf(c.pl)) |
| 73 | resp, err = c.pl.GetMetadata(ctx, &request) |
| 74 | } |
| 75 | case plugin.CommandGenerateEnvelope: |
| 76 | var request plugin.GenerateEnvelopeRequest |
| 77 | err = c.unmarshalRequest(&request) |
| 78 | if err == nil { |
| 79 | c.logger.Debugf("executing %s plugin's GenerateEnvelope function", reflect.TypeOf(c.pl)) |
| 80 | resp, err = c.pl.GenerateEnvelope(ctx, &request) |
| 81 | } |
| 82 | case plugin.CommandVerifySignature: |
| 83 | var request plugin.VerifySignatureRequest |
| 84 | err = c.unmarshalRequest(&request) |
| 85 | if err == nil { |
| 86 | c.logger.Debugf("executing %s plugin's VerifySignature function", reflect.TypeOf(c.pl)) |
| 87 | resp, err = c.pl.VerifySignature(ctx, &request) |
| 88 | } |
| 89 | case plugin.CommandDescribeKey: |
| 90 | var request plugin.DescribeKeyRequest |
| 91 | err = c.unmarshalRequest(&request) |
| 92 | if err == nil { |
| 93 | c.logger.Debugf("executing %s plugin's DescribeKey function", reflect.TypeOf(c.pl)) |
| 94 | resp, err = c.pl.DescribeKey(ctx, &request) |
| 95 | } |
| 96 | case plugin.CommandGenerateSignature: |
| 97 | var request plugin.GenerateSignatureRequest |
| 98 | err = c.unmarshalRequest(&request) |
| 99 | if err == nil { |
| 100 | c.logger.Debugf("executing %s plugin's GenerateSignature function", reflect.TypeOf(c.pl)) |
| 101 | resp, err = c.pl.GenerateSignature(ctx, &request) |
| 102 | } |
| 103 | case plugin.Version: |
| 104 | rescueStdOut() |
| 105 | c.printVersion(ctx) |
| 106 | return |
| 107 | default: |
| 108 | // should never happen |
| 109 | rescueStdOut() |
| 110 | deliverError(plugin.NewGenericError("something went wrong").Error()) |
| 111 | } |
| 112 | |
| 113 | op, pluginErr := c.marshalResponse(resp, err) |
| 114 | rescueStdOut() |
| 115 | if pluginErr != nil { |
| 116 | deliverError(pluginErr.Error()) |
| 117 | } |
| 118 | fmt.Print(op) |
| 119 | } |
| 120 | |
| 121 | // printVersion prints version of executable |
| 122 | func (c *CLI) printVersion(ctx context.Context) { |
| 123 | md := c.getMetadata(ctx, c.pl) |
| 124 | |
| 125 | fmt.Printf("%s - %s\nVersion: %s\n", md.Name, md.Description, md.Version) |
| 126 | } |
| 127 | |
| 128 | // validateArgs validate commands/arguments passed to executable. |
| 129 | func (c *CLI) validateArgs(ctx context.Context, args []string) { |
| 130 | md := c.getMetadata(ctx, c.pl) |
| 131 | if !(len(args) == 2 && slices.Contains(getValidArgs(md), args[1])) { |
| 132 | deliverError(fmt.Sprintf("Invalid command, valid commands are: %s", getValidArgsString(md))) |
| 133 | } |
| 134 | } |
| 135 | |
| 136 | // unmarshalRequest reads input from std.in and unmarshal it into given request struct |
| 137 | func (c *CLI) unmarshalRequest(request plugin.Request) error { |
| 138 | if err := json.NewDecoder(os.Stdin).Decode(request); err != nil { |
| 139 | c.logger.Errorf("%s unmarshalling error: %v", reflect.TypeOf(request), err) |
| 140 | return plugin.NewJSONParsingError(plugin.ErrorMsgMalformedInput) |
| 141 | } |
| 142 | |
| 143 | if err := request.Validate(); err != nil { |
| 144 | c.logger.Errorf("%s validation error: %v", reflect.TypeOf(request), err) |
| 145 | var plError *plugin.Error |
| 146 | if errors.As(err, &plError) { |
| 147 | return plugin.NewValidationErrorf("%s: %s", plugin.ErrorMsgMalformedInput, plError.Message) |
| 148 | } |
| 149 | return plugin.NewValidationErrorf("%s", plugin.ErrorMsgMalformedInput) |
| 150 | } |
| 151 | |
| 152 | return nil |
| 153 | } |
| 154 | |
| 155 | func (c *CLI) getMetadata(ctx context.Context, p plugin.Plugin) *plugin.GetMetadataResponse { |
| 156 | md, err := p.GetMetadata(ctx, &plugin.GetMetadataRequest{}) |
| 157 | if err != nil { |
| 158 | c.logger.Errorf("GetMetadataRequest error: %v", err) |
| 159 | deliverError("Error: Failed to get plugin metadata.") |
| 160 | } |
| 161 | return md |
| 162 | } |
| 163 | |
| 164 | // marshalResponse marshals the given response struct into json |
| 165 | func (c *CLI) marshalResponse(response any, err error) (string, *plugin.Error) { |
| 166 | if err != nil { |
| 167 | c.logger.Errorf("%s error: %v", reflect.TypeOf(response), err) |
| 168 | if plgErr, ok := err.(*plugin.Error); ok { |
| 169 | return "", plgErr |
| 170 | } |
| 171 | return "", plugin.NewGenericError(err.Error()) |
| 172 | } |
| 173 | |
| 174 | c.logger.Debug("marshalling response") |
| 175 | jsonResponse, err := json.Marshal(response) |
| 176 | if err != nil { |
| 177 | c.logger.Errorf("%s marshalling error: %v", reflect.TypeOf(response), err) |
| 178 | return "", plugin.NewGenericErrorf(plugin.ErrorMsgMalformedOutputFmt, err.Error()) |
| 179 | } |
| 180 | |
| 181 | c.logger.Debugf("%s response: %s", reflect.TypeOf(response), jsonResponse) |
| 182 | return string(jsonResponse), nil |
| 183 | } |