| 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 |
| 15 | |
| 16 | import ( |
| 17 | "context" |
| 18 | "fmt" |
| 19 | "io" |
| 20 | "log" |
| 21 | "os" |
| 22 | "os/exec" |
| 23 | "reflect" |
| 24 | "strings" |
| 25 | "testing" |
| 26 | |
| 27 | "github.com/notaryproject/notation-plugin-framework-go/internal/mock" |
| 28 | "github.com/notaryproject/notation-plugin-framework-go/plugin" |
| 29 | ) |
| 30 | |
| 31 | var cli, _ = New(mock.NewPlugin(false)) |
| 32 | var errorCli, _ = New(mock.NewPlugin(true)) |
| 33 | |
| 34 | func TestNewWithLogger(t *testing.T) { |
| 35 | _, err := NewWithLogger(nil, &discardLogger{}) |
| 36 | if err == nil { |
| 37 | t.Errorf("NewWithLogger() expected error but not found") |
| 38 | } |
| 39 | } |
| 40 | |
| 41 | func TestMarshalResponse(t *testing.T) { |
| 42 | res := plugin.GenerateEnvelopeResponse{ |
| 43 | SignatureEnvelope: []byte("envelope"), |
| 44 | Annotations: map[string]string{"key": "value"}, |
| 45 | SignatureEnvelopeType: "envelopeType", |
| 46 | } |
| 47 | op, err := cli.marshalResponse(res, nil) |
| 48 | if err != nil { |
| 49 | t.Errorf("Error found in marshalResponse: %v", err) |
| 50 | } |
| 51 | |
| 52 | expected := "{\"signatureEnvelope\":\"ZW52ZWxvcGU=\",\"signatureEnvelopeType\":\"envelopeType\",\"annotations\":{\"key\":\"value\"}}" |
| 53 | if !strings.EqualFold("{\"signatureEnvelope\":\"ZW52ZWxvcGU=\",\"signatureEnvelopeType\":\"envelopeType\",\"annotations\":{\"key\":\"value\"}}", op) { |
| 54 | t.Errorf("Not equal: \n expected: %s\n actual : %s", expected, op) |
| 55 | } |
| 56 | } |
| 57 | |
| 58 | func TestMarshalResponseError(t *testing.T) { |
| 59 | _, err := cli.marshalResponse(nil, fmt.Errorf("expected error thrown")) |
| 60 | assertErr(t, err, plugin.ErrorCodeGeneric) |
| 61 | |
| 62 | _, err = cli.marshalResponse(nil, plugin.NewValidationError("expected validation error thrown")) |
| 63 | assertErr(t, err, plugin.ErrorCodeValidation) |
| 64 | |
| 65 | _, err = cli.marshalResponse(make(chan int), nil) |
| 66 | assertErr(t, err, plugin.ErrorCodeGeneric) |
| 67 | } |
| 68 | |
| 69 | func TestUnmarshalRequest(t *testing.T) { |
| 70 | content := "{\"contractVersion\":\"1.0\",\"keyId\":\"someKeyId\",\"pluginConfig\":{\"pc1\":\"pk1\"}}" |
| 71 | closer := setupReader(content) |
| 72 | defer closer() |
| 73 | |
| 74 | var request plugin.DescribeKeyRequest |
| 75 | if err := cli.unmarshalRequest(&request); err != nil { |
| 76 | t.Errorf("unmarshalRequest() failed with error: %v", err) |
| 77 | } |
| 78 | |
| 79 | if request.ContractVersion != "1.0" || request.KeyID != "someKeyId" || request.PluginConfig["pc1"] != "pk1" { |
| 80 | t.Errorf("unmarshalRequest() returned incorrect struct") |
| 81 | } |
| 82 | } |
| 83 | |
| 84 | func TestUnmarshalRequestError(t *testing.T) { |
| 85 | closer := setupReader("InvalidJson") |
| 86 | defer closer() |
| 87 | |
| 88 | var request plugin.DescribeKeyRequest |
| 89 | err := cli.unmarshalRequest(&request) |
| 90 | if err == nil { |
| 91 | t.Errorf("unmarshalRequest() expected error but not found") |
| 92 | } |
| 93 | |
| 94 | plgErr, ok := err.(*plugin.Error) |
| 95 | if !ok { |
| 96 | t.Errorf("unmarshalRequest() expected error of type plugin.Error but found %s", reflect.TypeOf(err)) |
| 97 | } |
| 98 | |
| 99 | expectedErrStr := "{\"errorCode\":\"VALIDATION_ERROR\",\"errorMessage\":\"Input is not a valid JSON\"}" |
| 100 | if plgErr.Error() != expectedErrStr { |
| 101 | t.Errorf("unmarshalRequest() expected error string to be %s but found %s", expectedErrStr, plgErr.Error()) |
| 102 | } |
| 103 | } |
| 104 | |
| 105 | func TestGetMetadataError(t *testing.T) { |
| 106 | if os.Getenv("TEST_OS_EXIT") == "1" { |
| 107 | ctx := context.Background() |
| 108 | errorCli.Execute(ctx, []string{string(plugin.CommandGetMetadata)}) |
| 109 | return |
| 110 | } |
| 111 | cmd := exec.Command(os.Args[0], "-test.run=TestGetMetadataError") |
| 112 | cmd.Env = append(os.Environ(), "TEST_OS_EXIT=1") |
| 113 | err := cmd.Run() |
| 114 | if e, ok := err.(*exec.ExitError); ok && !e.Success() { |
| 115 | return |
| 116 | } |
| 117 | t.Errorf("process ran with err %v, want exit status 1", err) |
| 118 | } |
| 119 | |
| 120 | func TestExecuteSuccess(t *testing.T) { |
| 121 | sigGenCli, _ := New(mock.NewSigGeneratorPlugin(false)) |
| 122 | tests := map[string]struct { |
| 123 | c *CLI |
| 124 | in string |
| 125 | op string |
| 126 | }{ |
| 127 | string(plugin.CommandGetMetadata): { |
| 128 | c: cli, |
| 129 | in: "{}", |
| 130 | op: "{\"name\":\"Example Plugin\",\"description\":\"This is an description of example plugin. 🍺\",\"version\":\"1.0.0\",\"url\":\"https://example.com/notation/plugin\",\"capabilities\":[\"SIGNATURE_VERIFIER.TRUSTED_IDENTITY\",\"SIGNATURE_VERIFIER.REVOCATION_CHECK\",\"SIGNATURE_GENERATOR.ENVELOPE\"]}", |
| 131 | }, |
| 132 | string(plugin.Version): { |
| 133 | c: cli, |
| 134 | in: "", |
| 135 | op: "Example Plugin - This is an description of example plugin. 🍺\nVersion: 1.0.0\n", |
| 136 | }, |
| 137 | string(plugin.CommandGenerateEnvelope): { |
| 138 | c: cli, |
| 139 | in: "{\"contractVersion\":\"1.0\",\"keyId\":\"someKeyId\",\"payloadType\":\"somePT\",\"signatureEnvelopeType\":\"someSET\",\"payload\":\"em9w\"}", |
| 140 | op: "{\"signatureEnvelope\":\"\",\"signatureEnvelopeType\":\"someSET\",\"annotations\":{\"manifestAnntnKey1\":\"value1\"}}", |
| 141 | }, |
| 142 | string(plugin.CommandVerifySignature): { |
| 143 | c: cli, |
| 144 | in: "{\"contractVersion\":\"1.0\",\"signature\":{\"criticalAttributes\":{\"contentType\":\"someCT\",\"signingScheme\":\"someSigningScheme\"},\"unprocessedAttributes\":null,\"certificateChain\":[\"emFw\",\"em9w\"]},\"trustPolicy\":{\"trustedIdentities\":null,\"signatureVerification\":[\"SIGNATURE_GENERATOR.RAW\"]}}", |
| 145 | op: "{\"verificationResults\":{\"SIGNATURE_VERIFIER.REVOCATION_CHECK\":{\"success\":true,\"reason\":\"Not revoked\"},\"SIGNATURE_VERIFIER.TRUSTED_IDENTITY\":{\"success\":true,\"reason\":\"Valid trusted Identity\"}},\"processedAttributes\":[]}", |
| 146 | }, |
| 147 | string(plugin.CommandGenerateSignature): { |
| 148 | c: sigGenCli, |
| 149 | in: "{\"contractVersion\":\"1.0\",\"keyId\":\"someKeyId\",\"keySpec\":\"EC-384\",\"hashAlgorithm\":\"SHA-384\",\"payload\":\"em9w\"}", |
| 150 | op: "{\"keyId\":\"someKeyId\",\"signature\":\"YWJjZA==\",\"signingAlgorithm\":\"RSASSA-PSS-SHA-256\",\"certificateChain\":[\"YWJjZA==\",\"d3h5eg==\"]}", |
| 151 | }, |
| 152 | string(plugin.CommandDescribeKey): { |
| 153 | c: sigGenCli, |
| 154 | in: "{\"contractVersion\":\"1.0\",\"keyId\":\"someKeyId\"}", |
| 155 | op: "{\"keyId\":\"someKeyId\",\"keySpec\":\"RSA-2048\"}", |
| 156 | }, |
| 157 | } |
| 158 | for name, test := range tests { |
| 159 | t.Run(name, func(t *testing.T) { |
| 160 | closer := setupReader(test.in) |
| 161 | defer closer() |
| 162 | op := captureStdOut(func() { |
| 163 | test.c.Execute(context.Background(), []string{"notation", name}) |
| 164 | }) |
| 165 | if op != test.op { |
| 166 | t.Errorf("Execute() with '%s' args, expected '%s' but got '%s'", name, test.op, op) |
| 167 | } |
| 168 | }) |
| 169 | } |
| 170 | } |
| 171 | |
| 172 | func setupReader(content string) func() { |
| 173 | tmpfile, err := os.CreateTemp("", "example") |
| 174 | if err != nil { |
| 175 | log.Fatal(err) |
| 176 | } |
| 177 | |
| 178 | if _, err := tmpfile.Write([]byte(content)); err != nil { |
| 179 | log.Fatal(err) |
| 180 | } |
| 181 | |
| 182 | if _, err := tmpfile.Seek(0, 0); err != nil { |
| 183 | log.Fatal(err) |
| 184 | } |
| 185 | |
| 186 | oldStdin := os.Stdin |
| 187 | os.Stdin = tmpfile |
| 188 | return func() { |
| 189 | os.Remove(tmpfile.Name()) |
| 190 | os.Stdin = oldStdin // Restore original Stdin |
| 191 | |
| 192 | tmpfile.Close() |
| 193 | } |
| 194 | } |
| 195 | |
| 196 | func captureStdOut(f func()) string { |
| 197 | orig := os.Stdout |
| 198 | r, w, _ := os.Pipe() |
| 199 | os.Stdout = w |
| 200 | f() |
| 201 | os.Stdout = orig |
| 202 | w.Close() |
| 203 | out, _ := io.ReadAll(r) |
| 204 | return string(out) |
| 205 | } |
| 206 | |
| 207 | func assertErr(t *testing.T, err error, code plugin.ErrorCode) { |
| 208 | if plgErr, ok := err.(*plugin.Error); ok { |
| 209 | if reflect.DeepEqual(code, plgErr.ErrCode) { |
| 210 | return |
| 211 | } |
| 212 | t.Errorf("mismatch in error code: \n expected: %s\n actual : %s", code, plgErr.ErrCode) |
| 213 | } |
| 214 | t.Errorf("expected error of type PluginError but found %s", reflect.TypeOf(err)) |
| 215 | } |