Debian Codegraph @

plugin/plugin_test.go

raw
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
15
16 import (
17 "context"
18 "encoding/json"
19 "errors"
20 "os"
21 "reflect"
22 "runtime"
23 "strconv"
24 "strings"
25 "testing"
26 "time"
27
28 "github.com/notaryproject/notation-go/plugin/proto"
29 )
30
31 func TestGetMetadata(t *testing.T) {
32 t.Run("plugin error is in invalid json format", func(t *testing.T) {
33 exitErr := errors.New("unknown error")
34 stderr := []byte("sad")
35 expectedErrMsg := "invalid character 's' looking for beginning of value"
36 plugin := CLIPlugin{name: "test-plugin"}
37 executor = testCommander{stdout: nil, stderr: stderr, err: exitErr}
38 _, err := plugin.GetMetadata(context.Background(), &proto.GetMetadataRequest{})
39 if err.Error() != expectedErrMsg {
40 t.Fatalf("should error. got err = %v, want %v", err, expectedErrMsg)
41 }
42 })
43
44 t.Run("plugin error is a valid json", func(t *testing.T) {
45 stderr := []byte("{\"errorCode\":\"ACCESS_DENIED\"}")
46 pluginErr := errors.New("plugin errors")
47 wantErr := proto.RequestError{Code: proto.ErrorCodeAccessDenied}
48
49 plugin := CLIPlugin{}
50 executor = testCommander{stdout: nil, stderr: stderr, err: pluginErr}
51 _, err := plugin.GetMetadata(context.Background(), &proto.GetMetadataRequest{})
52 if !errors.Is(err, wantErr) {
53 t.Fatalf("should error. got err = %v, want %v", err, wantErr)
54 }
55 })
56
57 t.Run("plugin cause system error", func(t *testing.T) {
58 exitErr := errors.New("system error")
59 stderr := []byte("")
60 expectedErrMsg := "system error"
61 plugin := CLIPlugin{name: "test-plugin"}
62 executor = testCommander{stdout: nil, stderr: stderr, err: exitErr}
63 _, err := plugin.GetMetadata(context.Background(), &proto.GetMetadataRequest{})
64 if err.Error() != expectedErrMsg {
65 t.Fatalf("should error. got err = %v, want %v", err, expectedErrMsg)
66 }
67 })
68
69 }
70
71 func TestDescribeKey(t *testing.T) {
72 t.Run("DescribeKey test", func(t *testing.T) {
73 keyResp := proto.DescribeKeyResponse{KeyID: "1", KeySpec: "RSA-4096"}
74 output, err := json.Marshal(keyResp)
75 if err != nil {
76 t.Fatal("should not error.")
77 }
78 executor = testCommander{stdout: output, err: nil}
79
80 plugin := CLIPlugin{}
81 resp, err := plugin.DescribeKey(context.Background(), &proto.DescribeKeyRequest{})
82 if err != nil {
83 t.Fatalf("should not error. got err = %v", err)
84 }
85 if reflect.DeepEqual(resp, keyResp) {
86 t.Fatalf("DescribeKey() error. got: %+v, want: %+v", resp, keyResp)
87 }
88 })
89 }
90
91 func TestGenerateSignature(t *testing.T) {
92 t.Run("GenerateSignature test", func(t *testing.T) {
93 keyResp := proto.GenerateSignatureResponse{
94 KeyID: "1",
95 Signature: []byte("xxxxx"),
96 SigningAlgorithm: "ECDSA-SHA-256",
97 CertificateChain: [][]byte{{121, 132, 30, 42}},
98 }
99 output, err := json.Marshal(keyResp)
100 if err != nil {
101 t.Fatal("should not error.")
102 }
103 executor = testCommander{stdout: output, err: nil}
104
105 plugin := CLIPlugin{}
106 resp, err := plugin.GenerateSignature(context.Background(), &proto.GenerateSignatureRequest{})
107 if err != nil {
108 t.Fatalf("should not error. got err = %v", err)
109 }
110 if reflect.DeepEqual(resp, keyResp) {
111 t.Fatalf("GenerateSignature() error. got: %+v, want: %+v", resp, keyResp)
112 }
113 })
114 }
115
116 func TestGenerateEnvelope(t *testing.T) {
117 t.Run("GenerateEnvelope test", func(t *testing.T) {
118 keyResp := proto.GenerateEnvelopeResponse{
119 SignatureEnvelope: []byte("{}"),
120 SignatureEnvelopeType: "jws",
121 Annotations: map[string]string{},
122 }
123 output, err := json.Marshal(keyResp)
124 if err != nil {
125 t.Fatal("should not error.")
126 }
127 executor = testCommander{stdout: output, err: nil}
128
129 plugin := CLIPlugin{}
130 resp, err := plugin.GenerateEnvelope(context.Background(), &proto.GenerateEnvelopeRequest{})
131 if err != nil {
132 t.Fatalf("should not error. got err = %v", err)
133 }
134 if reflect.DeepEqual(resp, keyResp) {
135 t.Fatalf("GenerateEnvelope() error. got: %+v, want: %+v", resp, keyResp)
136 }
137 })
138 }
139
140 func TestVerifySignature(t *testing.T) {
141 t.Run("VerifySignature test", func(t *testing.T) {
142 keyResp := proto.VerifySignatureResponse{
143 VerificationResults: map[proto.Capability]*proto.VerificationResult{},
144 ProcessedAttributes: []interface{}{"attr1"},
145 }
146 output, err := json.Marshal(keyResp)
147 if err != nil {
148 t.Fatal("should not error.")
149 }
150 executor = testCommander{stdout: output, err: nil}
151
152 plugin := CLIPlugin{}
153 resp, err := plugin.VerifySignature(context.Background(), &proto.VerifySignatureRequest{})
154 if err != nil {
155 t.Fatalf("should not error. got err = %v", err)
156 }
157 if reflect.DeepEqual(resp, keyResp) {
158 t.Fatalf("VerifySignature() error. got: %+v, want: %+v", resp, keyResp)
159 }
160 })
161 }
162
163 func TestValidateMetadata(t *testing.T) {
164 tests := []struct {
165 m *proto.GetMetadataResponse
166 wantErr bool
167 }{
168 {&proto.GetMetadataResponse{}, true},
169 {&proto.GetMetadataResponse{Name: "name"}, true},
170 {&proto.GetMetadataResponse{Name: "name", Description: "friendly"}, true},
171 {&proto.GetMetadataResponse{Name: "name", Description: "friendly", Version: "1"}, true},
172 {&proto.GetMetadataResponse{Name: "name", Description: "friendly", Version: "1", URL: "example.com"}, true},
173 {&proto.GetMetadataResponse{Name: "name", Description: "friendly", Version: "1", URL: "example.com", Capabilities: []proto.Capability{"cap"}}, true},
174 {&proto.GetMetadataResponse{Name: "name", Description: "friendly", Version: "1", URL: "example.com", SupportedContractVersions: []string{"1.0"}}, true},
175 {&proto.GetMetadataResponse{Name: "name", Description: "friendly", Version: "1", URL: "example.com", SupportedContractVersions: []string{"1.0"}, Capabilities: []proto.Capability{"cap"}}, false},
176 }
177 for i, tt := range tests {
178 t.Run(strconv.Itoa(i), func(t *testing.T) {
179 if err := validate(tt.m); (err != nil) != tt.wantErr {
180 t.Errorf("GetMetadataResponse.Validate() error = %v, wantErr %v", err, tt.wantErr)
181 }
182 })
183 }
184 }
185
186 func TestNewCLIPlugin_Error(t *testing.T) {
187 ctx := context.Background()
188 t.Run("plugin directory exists without executable.", func(t *testing.T) {
189 p, err := NewCLIPlugin(ctx, "emptyplugin", "./testdata/plugins/emptyplugin/notation-emptyplugin")
190 if !errors.Is(err, os.ErrNotExist) {
191 t.Errorf("NewCLIPlugin() error = %v, want %v", err, os.ErrNotExist)
192 }
193 if p != nil {
194 t.Errorf("NewCLIPlugin() plugin = %v, want nil", p)
195 }
196 })
197
198 t.Run("plugin is not a regular file", func(t *testing.T) {
199 expectedErrMsg := "plugin executable file is not a regular file"
200 p, err := NewCLIPlugin(ctx, "badplugin", "./testdata/plugins/badplugin/notation-badplugin")
201 if err.Error() != expectedErrMsg {
202 t.Errorf("NewCLIPlugin() error = %v, want %v", err, expectedErrMsg)
203 }
204 if p != nil {
205 t.Errorf("NewCLIPlugin() plugin = %v, want nil", p)
206 }
207 })
208
209 t.Run("plugin timeout error", func(t *testing.T) {
210 if runtime.GOOS == "windows" {
211 t.Skip("skipping test on Windows")
212 }
213 expectedErrMsg := "'sleep 2' command execution timeout: signal: killed"
214 ctxWithTimout, cancel := context.WithTimeout(ctx, 10 * time.Millisecond)
215 defer cancel()
216
217 var twoSeconds proto.Command
218 twoSeconds = "2"
219 _, _, err := execCommander{}.Output(ctxWithTimout, "sleep", twoSeconds, nil);
220 if err == nil {
221 t.Errorf("execCommander{}.Output() expected error = %v, got nil", expectedErrMsg)
222 }
223 if err.Error() != expectedErrMsg {
224 t.Errorf("execCommander{}.Output() error = %v, want %v", err, expectedErrMsg)
225 }
226 })
227 }
228
229 func TestNewCLIPlugin_ValidError(t *testing.T) {
230 ctx := context.Background()
231 p, err := NewCLIPlugin(ctx, "foo", "./testdata/plugins/foo/notation-foo")
232 if err != nil {
233 t.Fatal("should no error.")
234 }
235 t.Run("command no response", func(t *testing.T) {
236 executor = testCommander{}
237 _, err := p.GetMetadata(ctx, &proto.GetMetadataRequest{})
238 if _, ok := err.(*PluginMalformedError); !ok {
239 t.Fatal("should return plugin validity error")
240 }
241 })
242
243 t.Run("invalid json", func(t *testing.T) {
244 executor = testCommander{stdout: []byte("content")}
245 _, err := p.GetMetadata(ctx, &proto.GetMetadataRequest{})
246 if _, ok := err.(*PluginMalformedError); !ok {
247 t.Fatal("should return plugin validity error")
248 }
249 })
250
251 t.Run("invalid metadata name", func(t *testing.T) {
252 executor = testCommander{stdout: metadataJSON(invalidMetadataName)}
253 _, err := p.GetMetadata(ctx, &proto.GetMetadataRequest{})
254 if !strings.Contains(err.Error(), "executable file name must be") {
255 t.Fatal("should fail the operation.")
256 }
257 })
258
259 t.Run("invalid metadata content", func(t *testing.T) {
260 executor = testCommander{stdout: metadataJSON(proto.GetMetadataResponse{Name: "foo"})}
261 _, err := p.GetMetadata(ctx, &proto.GetMetadataRequest{})
262 if _, ok := err.(*PluginMalformedError); !ok {
263 t.Fatal("should be plugin validity error.")
264 }
265 })
266
267 t.Run("valid", func(t *testing.T) {
268 executor = testCommander{stdout: metadataJSON(validMetadata)}
269 _, err := p.GetMetadata(ctx, &proto.GetMetadataRequest{})
270 if err != nil {
271 t.Fatalf("should valid. got err = %v", err)
272 }
273 metadata, err := p.GetMetadata(context.Background(), &proto.GetMetadataRequest{})
274 if err != nil {
275 t.Fatalf("should valid. got err = %v", err)
276 }
277 if !reflect.DeepEqual(metadata, &validMetadata) {
278 t.Fatalf("should be equal. got metadata = %+v, want %+v", metadata, validMetadata)
279 }
280 })
281
282 t.Run("invalid contract version", func(t *testing.T) {
283 executor = testCommander{stdout: metadataJSON(invalidContractVersionMetadata)}
284 _, err := p.GetMetadata(ctx, &proto.GetMetadataRequest{})
285 if err == nil {
286 t.Fatal("should have an invalid contract version error")
287 }
288 })
289 }