|
| 1 | +// |
| 2 | +// Copyright 2024-2026 The Chainloop Authors. |
| 3 | +// |
| 4 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +// you may not use this file except in compliance with the License. |
| 6 | +// You may obtain a copy of the License at |
| 7 | +// |
| 8 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +// |
| 10 | +// Unless required by applicable law or agreed to in writing, software |
| 11 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +// See the License for the specific language governing permissions and |
| 14 | +// limitations under the License. |
| 15 | + |
| 16 | +package biz |
| 17 | + |
| 18 | +import ( |
| 19 | + "fmt" |
| 20 | + "testing" |
| 21 | + |
| 22 | + "github.com/stretchr/testify/assert" |
| 23 | + "github.com/stretchr/testify/require" |
| 24 | +) |
| 25 | + |
| 26 | +func TestDecryptWrongPassphraseReturnsTypedError(t *testing.T) { |
| 27 | + t.Parallel() |
| 28 | + |
| 29 | + ciphertext, err := encrypt([]byte("hello attestation"), "correct-passphrase") |
| 30 | + require.NoError(t, err) |
| 31 | + |
| 32 | + // The passphrase that created the ciphertext still decrypts it. |
| 33 | + plaintext, err := decrypt(ciphertext, "correct-passphrase") |
| 34 | + require.NoError(t, err) |
| 35 | + assert.Equal(t, []byte("hello attestation"), plaintext) |
| 36 | + |
| 37 | + // A different passphrase is reported as a typed error so the service layer |
| 38 | + // can turn it into a client error instead of masking it as a server error. |
| 39 | + _, err = decrypt(ciphertext, "another-passphrase") |
| 40 | + require.Error(t, err) |
| 41 | + assert.True(t, IsErrInvalidPassphrase(err), "expected ErrInvalidPassphrase, got %T: %v", err, err) |
| 42 | +} |
| 43 | + |
| 44 | +// The read path wraps the decryption error with %w, so the typed error must |
| 45 | +// still be discoverable through errors.As. |
| 46 | +func TestErrInvalidPassphraseIsDiscoverableWhenWrapped(t *testing.T) { |
| 47 | + t.Parallel() |
| 48 | + |
| 49 | + wrapped := fmt.Errorf("failed to decrypt attestation state: %w", NewErrInvalidPassphrase()) |
| 50 | + assert.True(t, IsErrInvalidPassphrase(wrapped)) |
| 51 | +} |
0 commit comments