| 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 plugin provides the tooling to use the notation plugin. |
| 15 |
// |
| 16 |
// includes a CLIManager and a CLIPlugin implementation. |
| 17 |
package plugin |
| 18 |
|
| 19 |
import ( |
| 20 |
"bytes" |
| 21 |
"context" |
| 22 |
"encoding/json" |
| 23 |
"errors" |
| 24 |
"fmt" |
| 25 |
"os" |
| 26 |
"os/exec" |
| 27 |
"path/filepath" |
| 28 |
"strings" |
| 29 |
|
| 30 |
"github.com/notaryproject/notation-go/internal/io" |
| 31 |
"github.com/notaryproject/notation-go/internal/slices" |
| 32 |
"github.com/notaryproject/notation-go/log" |
| 33 |
"github.com/notaryproject/notation-go/plugin/proto" |
| 34 |
"github.com/notaryproject/notation-plugin-framework-go/plugin" |
| 35 |
) |
| 36 |
|
| 37 |
// maxPluginOutputSize is the maximum size of the plugin output. |
| 38 |
const maxPluginOutputSize = 64 * 1024 * 1024 // 64 MiB |
| 39 |
|
| 40 |
var executor commander = &execCommander{} // for unit test |
| 41 |
|
| 42 |
// GenericPlugin is the base requirement to be a plugin. |
| 43 |
// |
| 44 |
// Deprecated: GenericPlugin exists for historical compatibility and should not be used. |
| 45 |
// To access GenericPlugin, use the notation-plugin-framework-go's plugin.GenericPlugin type. |
| 46 |
type GenericPlugin = plugin.GenericPlugin |
| 47 |
|
| 48 |
// SignPlugin defines the required methods to be a SignPlugin. |
| 49 |
// |
| 50 |
// Deprecated: SignPlugin exists for historical compatibility and should not be used. |
| 51 |
// To access SignPlugin, use the notation-plugin-framework-go's plugin.SignPlugin type. |
| 52 |
type SignPlugin = plugin.SignPlugin |
| 53 |
|
| 54 |
// VerifyPlugin defines the required method to be a VerifyPlugin. |
| 55 |
// |
| 56 |
// Deprecated: VerifyPlugin exists for historical compatibility and should not be used. |
| 57 |
// To access VerifyPlugin, use the notation-plugin-framework-go's plugin.VerifyPlugin type. |
| 58 |
type VerifyPlugin = plugin.VerifyPlugin |
| 59 |
|
| 60 |
// Plugin defines required methods to be a Plugin. |
| 61 |
// |
| 62 |
// Deprecated: Plugin exists for historical compatibility and should not be used. |
| 63 |
// To access Plugin, use the notation-plugin-framework-go's plugin.Plugin type. |
| 64 |
type Plugin = plugin.Plugin |
| 65 |
|
| 66 |
// CLIPlugin implements Plugin interface to CLI plugins. |
| 67 |
type CLIPlugin struct { |
| 68 |
name string |
| 69 |
path string |
| 70 |
} |
| 71 |
|
| 72 |
// NewCLIPlugin returns a *CLIPlugin. |
| 73 |
func NewCLIPlugin(ctx context.Context, name, path string) (*CLIPlugin, error) { |
| 74 |
// validate file existence |
| 75 |
fi, err := os.Stat(path) |
| 76 |
if err != nil { |
| 77 |
// Ignore any file which we cannot Stat |
| 78 |
// (e.g. due to permissions or anything else). |
| 79 |
return nil, fmt.Errorf("plugin executable file is either not found or inaccessible: %w", err) |
| 80 |
} |
| 81 |
if !fi.Mode().IsRegular() { |
| 82 |
// Ignore non-regular files. |
| 83 |
return nil, ErrNotRegularFile |
| 84 |
} |
| 85 |
|
| 86 |
// generate plugin |
| 87 |
return &CLIPlugin{ |
| 88 |
name: name, |
| 89 |
path: path, |
| 90 |
}, nil |
| 91 |
} |
| 92 |
|
| 93 |
// GetMetadata returns the metadata information of the plugin. |
| 94 |
func (p *CLIPlugin) GetMetadata(ctx context.Context, req *plugin.GetMetadataRequest) (*plugin.GetMetadataResponse, error) { |
| 95 |
var metadata plugin.GetMetadataResponse |
| 96 |
err := run(ctx, p.name, p.path, req, &metadata) |
| 97 |
if err != nil { |
| 98 |
return nil, err |
| 99 |
} |
| 100 |
// validate metadata |
| 101 |
if err = validate(&metadata); err != nil { |
| 102 |
return nil, &PluginMalformedError{ |
| 103 |
Msg: fmt.Sprintf("metadata validation failed for plugin %s: %s", p.name, err), |
| 104 |
InnerError: err, |
| 105 |
} |
| 106 |
} |
| 107 |
if metadata.Name != p.name { |
| 108 |
return nil, fmt.Errorf("plugin executable file name must be %q instead of %q", binName(metadata.Name), filepath.Base(p.path)) |
| 109 |
} |
| 110 |
return &metadata, nil |
| 111 |
} |
| 112 |
|
| 113 |
// DescribeKey returns the KeySpec of a key. |
| 114 |
// |
| 115 |
// if ContractVersion is not set, it will be set by the function. |
| 116 |
func (p *CLIPlugin) DescribeKey(ctx context.Context, req *plugin.DescribeKeyRequest) (*plugin.DescribeKeyResponse, error) { |
| 117 |
if req.ContractVersion == "" { |
| 118 |
req.ContractVersion = plugin.ContractVersion |
| 119 |
} |
| 120 |
|
| 121 |
var resp plugin.DescribeKeyResponse |
| 122 |
err := run(ctx, p.name, p.path, req, &resp) |
| 123 |
return &resp, err |
| 124 |
} |
| 125 |
|
| 126 |
// GenerateSignature generates the raw signature based on the request. |
| 127 |
// |
| 128 |
// if ContractVersion is not set, it will be set by the function. |
| 129 |
func (p *CLIPlugin) GenerateSignature(ctx context.Context, req *plugin.GenerateSignatureRequest) (*plugin.GenerateSignatureResponse, error) { |
| 130 |
if req.ContractVersion == "" { |
| 131 |
req.ContractVersion = plugin.ContractVersion |
| 132 |
} |
| 133 |
|
| 134 |
var resp plugin.GenerateSignatureResponse |
| 135 |
err := run(ctx, p.name, p.path, req, &resp) |
| 136 |
return &resp, err |
| 137 |
} |
| 138 |
|
| 139 |
// GenerateEnvelope generates the Envelope with signature based on the request. |
| 140 |
// |
| 141 |
// if ContractVersion is not set, it will be set by the function. |
| 142 |
func (p *CLIPlugin) GenerateEnvelope(ctx context.Context, req *plugin.GenerateEnvelopeRequest) (*plugin.GenerateEnvelopeResponse, error) { |
| 143 |
if req.ContractVersion == "" { |
| 144 |
req.ContractVersion = plugin.ContractVersion |
| 145 |
} |
| 146 |
|
| 147 |
var resp plugin.GenerateEnvelopeResponse |
| 148 |
err := run(ctx, p.name, p.path, req, &resp) |
| 149 |
return &resp, err |
| 150 |
} |
| 151 |
|
| 152 |
// VerifySignature validates the signature based on the request. |
| 153 |
// |
| 154 |
// if ContractVersion is not set, it will be set by the function. |
| 155 |
func (p *CLIPlugin) VerifySignature(ctx context.Context, req *plugin.VerifySignatureRequest) (*plugin.VerifySignatureResponse, error) { |
| 156 |
if req.ContractVersion == "" { |
| 157 |
req.ContractVersion = plugin.ContractVersion |
| 158 |
} |
| 159 |
|
| 160 |
var resp plugin.VerifySignatureResponse |
| 161 |
err := run(ctx, p.name, p.path, req, &resp) |
| 162 |
return &resp, err |
| 163 |
} |
| 164 |
|
| 165 |
func run(ctx context.Context, pluginName string, pluginPath string, req plugin.Request, resp interface{}) error { |
| 166 |
logger := log.GetLogger(ctx) |
| 167 |
|
| 168 |
// serialize request |
| 169 |
data, err := json.Marshal(req) |
| 170 |
if err != nil { |
| 171 |
logger.Errorf("Failed to marshal request object: %+v", req) |
| 172 |
return fmt.Errorf("failed to marshal request object: %w", err) |
| 173 |
} |
| 174 |
|
| 175 |
logger.Debugf("Plugin %s request: %s", req.Command(), string(data)) |
| 176 |
// execute request |
| 177 |
stdout, stderr, err := executor.Output(ctx, pluginPath, req.Command(), data) |
| 178 |
if err != nil { |
| 179 |
logger.Errorf("plugin %s execution status: %v", req.Command(), err) |
| 180 |
|
| 181 |
if len(stderr) == 0 { |
| 182 |
// if stderr is empty, it is possible that the plugin is not |
| 183 |
// running properly. |
| 184 |
logger.Errorf("failed to execute the %s command for plugin %s: %s", req.Command(), pluginName, err) |
| 185 |
return &PluginExecutableFileError{ |
| 186 |
InnerError: err, |
| 187 |
} |
| 188 |
} else { |
| 189 |
var re proto.RequestError |
| 190 |
jsonErr := json.Unmarshal(stderr, &re) |
| 191 |
if jsonErr != nil { |
| 192 |
logger.Errorf("failed to execute the %s command for plugin %s: %s", req.Command(), pluginName, strings.TrimSuffix(string(stderr), "\n")) |
| 193 |
return &PluginMalformedError{ |
| 194 |
InnerError: jsonErr, |
| 195 |
} |
| 196 |
} |
| 197 |
logger.Errorf("failed to execute the %s command for plugin %s: %s: %w", req.Command(), pluginName, re.Code, re) |
| 198 |
return re |
| 199 |
} |
| 200 |
} |
| 201 |
|
| 202 |
logger.Debugf("Plugin %s response: %s", req.Command(), string(stdout)) |
| 203 |
// deserialize response |
| 204 |
if err = json.Unmarshal(stdout, resp); err != nil { |
| 205 |
logger.Errorf("failed to unmarshal plugin %s response: %w", req.Command(), err) |
| 206 |
return &PluginMalformedError{ |
| 207 |
Msg: fmt.Sprintf("failed to unmarshal the response of %s command for plugin %s", req.Command(), pluginName), |
| 208 |
InnerError: err, |
| 209 |
} |
| 210 |
} |
| 211 |
return nil |
| 212 |
} |
| 213 |
|
| 214 |
// commander is defined for mocking purposes. |
| 215 |
type commander interface { |
| 216 |
// Output runs the command, passing req to the stdin. |
| 217 |
// It only returns an error if the binary can't be executed. |
| 218 |
// Returns stdout if err is nil, stderr if err is not nil. |
| 219 |
Output(ctx context.Context, path string, command plugin.Command, req []byte) (stdout []byte, stderr []byte, err error) |
| 220 |
} |
| 221 |
|
| 222 |
// execCommander implements the commander interface using exec.Command(). |
| 223 |
type execCommander struct{} |
| 224 |
|
| 225 |
func (c execCommander) Output(ctx context.Context, name string, command plugin.Command, req []byte) ([]byte, []byte, error) { |
| 226 |
var stdout, stderr bytes.Buffer |
| 227 |
cmd := exec.CommandContext(ctx, name, string(command)) |
| 228 |
cmd.Stdin = bytes.NewReader(req) |
| 229 |
// The limit writer will be handled by the caller in run() by comparing the |
| 230 |
// bytes written with the expected length of the bytes. |
| 231 |
cmd.Stderr = io.LimitWriter(&stderr, maxPluginOutputSize) |
| 232 |
cmd.Stdout = io.LimitWriter(&stdout, maxPluginOutputSize) |
| 233 |
err := cmd.Run() |
| 234 |
if err != nil { |
| 235 |
if errors.Is(ctx.Err(), context.DeadlineExceeded) { |
| 236 |
return nil, stderr.Bytes(), fmt.Errorf("'%s %s' command execution timeout: %w", name, string(command), err) |
| 237 |
} |
| 238 |
return nil, stderr.Bytes(), err |
| 239 |
} |
| 240 |
return stdout.Bytes(), nil, nil |
| 241 |
} |
| 242 |
|
| 243 |
// validate checks if the metadata is correctly populated. |
| 244 |
func validate(metadata *plugin.GetMetadataResponse) error { |
| 245 |
if metadata.Name == "" { |
| 246 |
return errors.New("empty name") |
| 247 |
} |
| 248 |
if metadata.Description == "" { |
| 249 |
return errors.New("empty description") |
| 250 |
} |
| 251 |
if metadata.Version == "" { |
| 252 |
return errors.New("empty version") |
| 253 |
} |
| 254 |
if metadata.URL == "" { |
| 255 |
return errors.New("empty url") |
| 256 |
} |
| 257 |
if len(metadata.Capabilities) == 0 { |
| 258 |
return errors.New("empty capabilities") |
| 259 |
} |
| 260 |
if len(metadata.SupportedContractVersions) == 0 { |
| 261 |
return errors.New("supported contract versions not specified") |
| 262 |
} |
| 263 |
if !slices.Contains(metadata.SupportedContractVersions, plugin.ContractVersion) { |
| 264 |
return fmt.Errorf( |
| 265 |
"contract version %q is not in the list of the plugin supported versions %v", |
| 266 |
plugin.ContractVersion, metadata.SupportedContractVersions, |
| 267 |
) |
| 268 |
} |
| 269 |
return nil |
| 270 |
} |