//nolint:testpackage // white-box tests exercise unexported internals package cli import ( "path/filepath" "testing" "github.com/spf13/afero" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) const testFlagSignKey = "--sign-key" // TestGenAndFreshenSignWithKeyFile runs gen, then freshen after a file is // added, with --sign-key naming a key file: one key with no passphrase and // one protected by the passphrase in MFER_SIGN_KEY_PASSPHRASE. check // --require-signature must accept each manifest as signed by that key. // freshen leaves its manifest out of the listing only on the real // filesystem, so the test uses that. func TestGenAndFreshenSignWithKeyFile(t *testing.T) { for name, passphrase := range map[string][]byte{ "unprotected": nil, "protected": []byte("passphrase"), } { t.Run(name, func(t *testing.T) { t.Setenv(envSignKeyPassphrase, string(passphrase)) secretKey, fingerprint := testSecretKey(t, passphrase) fs := afero.NewOsFs() keyFile := filepath.Join(t.TempDir(), "key.asc") root := t.TempDir() manifestPath := filepath.Join(root, defaultManifestName) require.NoError(t, afero.WriteFile(fs, keyFile, secretKey, 0o600)) writeTestFile(t, fs, filepath.Join(root, testFileTxt), "hello") opts := testOpts([]string{ testApp, cmdGenerate, "-q", testFlagSignKey, keyFile, "-o", manifestPath, root, }, fs) require.Equal(t, 0, runCLI(opts), testStderr(t, opts)) check := []string{ testApp, cmdCheck, "-q", "--" + flagRequireSignature, fingerprint, manifestPath, } opts = testOpts(check, fs) require.Equal(t, 0, runCLI(opts), testStderr(t, opts)) writeTestFile(t, fs, filepath.Join(root, "added.txt"), "added") opts = testOpts([]string{ testApp, cmdFreshen, "-q", testFlagSignKey, keyFile, manifestPath, }, fs) require.Equal(t, 0, runCLI(opts), testStderr(t, opts)) opts = testOpts(check, fs) require.Equal(t, 0, runCLI(opts), testStderr(t, opts)) assert.Len(t, manifestFiles(t, fs, manifestPath), 2) }) } } // TestSignWithProtectedKeyNeedsPassphrase runs gen with a protected key, // with MFER_SIGN_KEY_PASSPHRASE empty and no terminal to ask on. gen must // fail, naming the variable, and write no manifest. func TestSignWithProtectedKeyNeedsPassphrase(t *testing.T) { t.Setenv(envSignKeyPassphrase, "") secretKey, _ := testSecretKey(t, []byte("secret")) fs := afero.NewMemMapFs() require.NoError(t, afero.WriteFile(fs, "/key.asc", secretKey, 0o600)) require.NoError(t, fs.MkdirAll(testDir, 0o755)) writeTestFile(t, fs, testFile1, "hello") opts := testOpts([]string{ testApp, cmdGenerate, "-q", testFlagSignKey, "/key.asc", "-o", testMF, testDir, }, fs) assert.Equal(t, 1, runCLI(opts)) assert.Contains(t, testStderr(t, opts), "signing key is protected: set MFER_SIGN_KEY_PASSPHRASE to its passphrase") exists, err := afero.Exists(fs, testMF) require.NoError(t, err) assert.False(t, exists) }