cli/command/trust: remove deprecated io/ioutil and use t.TempDir()

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
This commit is contained in:
Sebastiaan van Stijn 2022-02-25 14:33:57 +01:00
parent e0299ff862
commit b5dce3c9e6
No known key found for this signature in database
GPG Key ID: 76698F39D527CE8C
12 changed files with 80 additions and 159 deletions

View File

@ -1,8 +1,6 @@
package trust package trust
import ( import (
"io/ioutil"
"os"
"testing" "testing"
"github.com/theupdateframework/notary/client" "github.com/theupdateframework/notary/client"
@ -12,11 +10,7 @@ import (
) )
func TestGetOrGenerateNotaryKeyAndInitRepo(t *testing.T) { func TestGetOrGenerateNotaryKeyAndInitRepo(t *testing.T) {
tmpDir, err := ioutil.TempDir("", "notary-test-") notaryRepo, err := client.NewFileCachedRepository(t.TempDir(), "gun", "https://localhost", nil, passphrase.ConstantRetriever(passwd), trustpinning.TrustPinConfig{})
assert.NilError(t, err)
defer os.RemoveAll(tmpDir)
notaryRepo, err := client.NewFileCachedRepository(tmpDir, "gun", "https://localhost", nil, passphrase.ConstantRetriever(passwd), trustpinning.TrustPinConfig{})
assert.NilError(t, err) assert.NilError(t, err)
err = getOrGenerateRootKeyAndInitRepo(notaryRepo) err = getOrGenerateRootKeyAndInitRepo(notaryRepo)

View File

@ -5,7 +5,6 @@ import (
"context" "context"
"encoding/hex" "encoding/hex"
"io" "io"
"io/ioutil"
"testing" "testing"
"github.com/docker/cli/cli/trust" "github.com/docker/cli/cli/trust"
@ -65,7 +64,7 @@ func TestTrustInspectPrettyCommandErrors(t *testing.T) {
cmd := newInspectCommand( cmd := newInspectCommand(
test.NewFakeCli(&fakeClient{})) test.NewFakeCli(&fakeClient{}))
cmd.SetArgs(tc.args) cmd.SetArgs(tc.args)
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
cmd.Flags().Set("pretty", "true") cmd.Flags().Set("pretty", "true")
assert.ErrorContains(t, cmd.Execute(), tc.expectedError) assert.ErrorContains(t, cmd.Execute(), tc.expectedError)
} }
@ -77,7 +76,7 @@ func TestTrustInspectPrettyCommandOfflineErrors(t *testing.T) {
cmd := newInspectCommand(cli) cmd := newInspectCommand(cli)
cmd.Flags().Set("pretty", "true") cmd.Flags().Set("pretty", "true")
cmd.SetArgs([]string{"nonexistent-reg-name.io/image"}) cmd.SetArgs([]string{"nonexistent-reg-name.io/image"})
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
assert.ErrorContains(t, cmd.Execute(), "No signatures or cannot access nonexistent-reg-name.io/image") assert.ErrorContains(t, cmd.Execute(), "No signatures or cannot access nonexistent-reg-name.io/image")
cli = test.NewFakeCli(&fakeClient{}) cli = test.NewFakeCli(&fakeClient{})
@ -85,7 +84,7 @@ func TestTrustInspectPrettyCommandOfflineErrors(t *testing.T) {
cmd = newInspectCommand(cli) cmd = newInspectCommand(cli)
cmd.Flags().Set("pretty", "true") cmd.Flags().Set("pretty", "true")
cmd.SetArgs([]string{"nonexistent-reg-name.io/image:tag"}) cmd.SetArgs([]string{"nonexistent-reg-name.io/image:tag"})
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
assert.ErrorContains(t, cmd.Execute(), "No signatures or cannot access nonexistent-reg-name.io/image") assert.ErrorContains(t, cmd.Execute(), "No signatures or cannot access nonexistent-reg-name.io/image")
} }
@ -95,7 +94,7 @@ func TestTrustInspectPrettyCommandUninitializedErrors(t *testing.T) {
cmd := newInspectCommand(cli) cmd := newInspectCommand(cli)
cmd.Flags().Set("pretty", "true") cmd.Flags().Set("pretty", "true")
cmd.SetArgs([]string{"reg/unsigned-img"}) cmd.SetArgs([]string{"reg/unsigned-img"})
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
assert.ErrorContains(t, cmd.Execute(), "No signatures or cannot access reg/unsigned-img") assert.ErrorContains(t, cmd.Execute(), "No signatures or cannot access reg/unsigned-img")
cli = test.NewFakeCli(&fakeClient{}) cli = test.NewFakeCli(&fakeClient{})
@ -103,7 +102,7 @@ func TestTrustInspectPrettyCommandUninitializedErrors(t *testing.T) {
cmd = newInspectCommand(cli) cmd = newInspectCommand(cli)
cmd.Flags().Set("pretty", "true") cmd.Flags().Set("pretty", "true")
cmd.SetArgs([]string{"reg/unsigned-img:tag"}) cmd.SetArgs([]string{"reg/unsigned-img:tag"})
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
assert.ErrorContains(t, cmd.Execute(), "No signatures or cannot access reg/unsigned-img:tag") assert.ErrorContains(t, cmd.Execute(), "No signatures or cannot access reg/unsigned-img:tag")
} }
@ -113,7 +112,7 @@ func TestTrustInspectPrettyCommandEmptyNotaryRepoErrors(t *testing.T) {
cmd := newInspectCommand(cli) cmd := newInspectCommand(cli)
cmd.Flags().Set("pretty", "true") cmd.Flags().Set("pretty", "true")
cmd.SetArgs([]string{"reg/img:unsigned-tag"}) cmd.SetArgs([]string{"reg/img:unsigned-tag"})
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
assert.NilError(t, cmd.Execute()) assert.NilError(t, cmd.Execute())
assert.Check(t, is.Contains(cli.OutBuffer().String(), "No signatures for reg/img:unsigned-tag")) assert.Check(t, is.Contains(cli.OutBuffer().String(), "No signatures for reg/img:unsigned-tag"))
assert.Check(t, is.Contains(cli.OutBuffer().String(), "Administrative keys for reg/img")) assert.Check(t, is.Contains(cli.OutBuffer().String(), "Administrative keys for reg/img"))
@ -123,7 +122,7 @@ func TestTrustInspectPrettyCommandEmptyNotaryRepoErrors(t *testing.T) {
cmd = newInspectCommand(cli) cmd = newInspectCommand(cli)
cmd.Flags().Set("pretty", "true") cmd.Flags().Set("pretty", "true")
cmd.SetArgs([]string{"reg/img"}) cmd.SetArgs([]string{"reg/img"})
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
assert.NilError(t, cmd.Execute()) assert.NilError(t, cmd.Execute())
assert.Check(t, is.Contains(cli.OutBuffer().String(), "No signatures for reg/img")) assert.Check(t, is.Contains(cli.OutBuffer().String(), "No signatures for reg/img"))
assert.Check(t, is.Contains(cli.OutBuffer().String(), "Administrative keys for reg/img")) assert.Check(t, is.Contains(cli.OutBuffer().String(), "Administrative keys for reg/img"))

View File

@ -1,7 +1,7 @@
package trust package trust
import ( import (
"io/ioutil" "io"
"testing" "testing"
"github.com/docker/cli/cli/trust" "github.com/docker/cli/cli/trust"
@ -38,7 +38,7 @@ func TestTrustInspectCommandErrors(t *testing.T) {
test.NewFakeCli(&fakeClient{})) test.NewFakeCli(&fakeClient{}))
cmd.Flags().Set("pretty", "true") cmd.Flags().Set("pretty", "true")
cmd.SetArgs(tc.args) cmd.SetArgs(tc.args)
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
assert.ErrorContains(t, cmd.Execute(), tc.expectedError) assert.ErrorContains(t, cmd.Execute(), tc.expectedError)
} }
} }
@ -85,7 +85,7 @@ func TestTrustInspectCommandRepositoryErrors(t *testing.T) {
cli.SetNotaryClient(tc.notaryRepository) cli.SetNotaryClient(tc.notaryRepository)
cmd := newInspectCommand(cli) cmd := newInspectCommand(cli)
cmd.SetArgs(tc.args) cmd.SetArgs(tc.args)
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
assert.ErrorContains(t, cmd.Execute(), tc.err) assert.ErrorContains(t, cmd.Execute(), tc.err)
if tc.golden != "" { if tc.golden != "" {
golden.Assert(t, cli.OutBuffer().String(), tc.golden) golden.Assert(t, cli.OutBuffer().String(), tc.golden)

View File

@ -3,7 +3,6 @@ package trust
import ( import (
"encoding/pem" "encoding/pem"
"fmt" "fmt"
"io/ioutil"
"os" "os"
"path/filepath" "path/filepath"
"regexp" "regexp"
@ -126,7 +125,7 @@ func writePubKeyPEMToDir(pubPEM pem.Block, keyName, workingDir string) (string,
// Output the public key to a file in the CWD or specified dir // Output the public key to a file in the CWD or specified dir
pubFileName := strings.Join([]string{keyName, "pub"}, ".") pubFileName := strings.Join([]string{keyName, "pub"}, ".")
pubFilePath := filepath.Join(workingDir, pubFileName) pubFilePath := filepath.Join(workingDir, pubFileName)
if err := ioutil.WriteFile(pubFilePath, pem.EncodeToMemory(&pubPEM), notary.PrivNoExecPerms); err != nil { if err := os.WriteFile(pubFilePath, pem.EncodeToMemory(&pubPEM), notary.PrivNoExecPerms); err != nil {
return "", errors.Wrapf(err, "failed to write public key to %s", pubFilePath) return "", errors.Wrapf(err, "failed to write public key to %s", pubFilePath)
} }
return pubFilePath, nil return pubFilePath, nil

View File

@ -3,7 +3,7 @@ package trust
import ( import (
"encoding/pem" "encoding/pem"
"fmt" "fmt"
"io/ioutil" "io"
"os" "os"
"path/filepath" "path/filepath"
"testing" "testing"
@ -35,28 +35,20 @@ func TestTrustKeyGenerateErrors(t *testing.T) {
}, },
} }
tmpDir, err := ioutil.TempDir("", "docker-key-generate-test-") config.SetDir(t.TempDir())
assert.NilError(t, err)
defer os.RemoveAll(tmpDir)
config.SetDir(tmpDir)
for _, tc := range testCases { for _, tc := range testCases {
cli := test.NewFakeCli(&fakeClient{}) cli := test.NewFakeCli(&fakeClient{})
cmd := newKeyGenerateCommand(cli) cmd := newKeyGenerateCommand(cli)
cmd.SetArgs(tc.args) cmd.SetArgs(tc.args)
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
assert.ErrorContains(t, cmd.Execute(), tc.expectedError) assert.ErrorContains(t, cmd.Execute(), tc.expectedError)
} }
} }
func TestGenerateKeySuccess(t *testing.T) { func TestGenerateKeySuccess(t *testing.T) {
pubKeyCWD, err := ioutil.TempDir("", "pub-keys-") pubKeyCWD := t.TempDir()
assert.NilError(t, err) privKeyStorageDir := t.TempDir()
defer os.RemoveAll(pubKeyCWD)
privKeyStorageDir, err := ioutil.TempDir("", "priv-keys-")
assert.NilError(t, err)
defer os.RemoveAll(privKeyStorageDir)
passwd := "password" passwd := "password"
cannedPasswordRetriever := passphrase.ConstantRetriever(passwd) cannedPasswordRetriever := passphrase.ConstantRetriever(passwd)
@ -79,7 +71,7 @@ func TestGenerateKeySuccess(t *testing.T) {
_, err = os.Stat(expectedPrivKeyDir) _, err = os.Stat(expectedPrivKeyDir)
assert.NilError(t, err) assert.NilError(t, err)
keyFiles, err := ioutil.ReadDir(expectedPrivKeyDir) keyFiles, err := os.ReadDir(expectedPrivKeyDir)
assert.NilError(t, err) assert.NilError(t, err)
assert.Check(t, is.Len(keyFiles, 1)) assert.Check(t, is.Len(keyFiles, 1))
privKeyFilePath := filepath.Join(expectedPrivKeyDir, keyFiles[0].Name()) privKeyFilePath := filepath.Join(expectedPrivKeyDir, keyFiles[0].Name())
@ -87,7 +79,7 @@ func TestGenerateKeySuccess(t *testing.T) {
// verify the key content // verify the key content
privFrom, _ := os.OpenFile(privKeyFilePath, os.O_RDONLY, notary.PrivExecPerms) privFrom, _ := os.OpenFile(privKeyFilePath, os.O_RDONLY, notary.PrivExecPerms)
defer privFrom.Close() defer privFrom.Close()
fromBytes, _ := ioutil.ReadAll(privFrom) fromBytes, _ := io.ReadAll(privFrom)
privKeyPEM, _ := pem.Decode(fromBytes) privKeyPEM, _ := pem.Decode(fromBytes)
assert.Check(t, is.Equal(keyName, privKeyPEM.Headers["role"])) assert.Check(t, is.Equal(keyName, privKeyPEM.Headers["role"]))
// the default GUN is empty // the default GUN is empty
@ -106,17 +98,15 @@ func TestGenerateKeySuccess(t *testing.T) {
_, err = os.Stat(expectedPubKeyPath) _, err = os.Stat(expectedPubKeyPath)
assert.NilError(t, err) assert.NilError(t, err)
// check that the public key is the only file output in CWD // check that the public key is the only file output in CWD
cwdKeyFiles, err := ioutil.ReadDir(pubKeyCWD) cwdKeyFiles, err := os.ReadDir(pubKeyCWD)
assert.NilError(t, err) assert.NilError(t, err)
assert.Check(t, is.Len(cwdKeyFiles, 1)) assert.Check(t, is.Len(cwdKeyFiles, 1))
} }
func TestValidateKeyArgs(t *testing.T) { func TestValidateKeyArgs(t *testing.T) {
pubKeyCWD, err := ioutil.TempDir("", "pub-keys-") pubKeyCWD := t.TempDir()
assert.NilError(t, err)
defer os.RemoveAll(pubKeyCWD)
err = validateKeyArgs("a", pubKeyCWD) err := validateKeyArgs("a", pubKeyCWD)
assert.NilError(t, err) assert.NilError(t, err)
err = validateKeyArgs("a/b", pubKeyCWD) err = validateKeyArgs("a/b", pubKeyCWD)
@ -125,7 +115,7 @@ func TestValidateKeyArgs(t *testing.T) {
err = validateKeyArgs("-", pubKeyCWD) err = validateKeyArgs("-", pubKeyCWD)
assert.Error(t, err, "key name \"-\" must start with lowercase alphanumeric characters and can include \"-\" or \"_\" after the first character") assert.Error(t, err, "key name \"-\" must start with lowercase alphanumeric characters and can include \"-\" or \"_\" after the first character")
assert.NilError(t, ioutil.WriteFile(filepath.Join(pubKeyCWD, "a.pub"), []byte("abc"), notary.PrivExecPerms)) assert.NilError(t, os.WriteFile(filepath.Join(pubKeyCWD, "a.pub"), []byte("abc"), notary.PrivExecPerms))
err = validateKeyArgs("a", pubKeyCWD) err = validateKeyArgs("a", pubKeyCWD)
assert.Error(t, err, fmt.Sprintf("public key file already exists: \"%s\"", filepath.Join(pubKeyCWD, "a.pub"))) assert.Error(t, err, fmt.Sprintf("public key file already exists: \"%s\"", filepath.Join(pubKeyCWD, "a.pub")))

View File

@ -4,7 +4,7 @@ import (
"bytes" "bytes"
"encoding/pem" "encoding/pem"
"fmt" "fmt"
"io/ioutil" "io"
"os" "os"
"runtime" "runtime"
@ -86,7 +86,7 @@ func getPrivKeyBytesFromPath(keyPath string) ([]byte, error) {
} }
defer from.Close() defer from.Close()
return ioutil.ReadAll(from) return io.ReadAll(from)
} }
func loadPrivKeyBytesToStore(privKeyBytes []byte, privKeyImporters []trustmanager.Importer, keyPath, keyName string, passRet notary.PassRetriever) error { func loadPrivKeyBytesToStore(privKeyBytes []byte, privKeyImporters []trustmanager.Importer, keyPath, keyName string, passRet notary.PassRetriever) error {

View File

@ -3,7 +3,7 @@ package trust
import ( import (
"encoding/pem" "encoding/pem"
"fmt" "fmt"
"io/ioutil" "io"
"os" "os"
"path/filepath" "path/filepath"
"runtime" "runtime"
@ -56,16 +56,13 @@ func TestTrustKeyLoadErrors(t *testing.T) {
expectedOutput: "", expectedOutput: "",
}, },
} }
tmpDir, err := ioutil.TempDir("", "docker-key-load-test-") config.SetDir(t.TempDir())
assert.NilError(t, err)
defer os.RemoveAll(tmpDir)
config.SetDir(tmpDir)
for _, tc := range testCases { for _, tc := range testCases {
cli := test.NewFakeCli(&fakeClient{}) cli := test.NewFakeCli(&fakeClient{})
cmd := newKeyLoadCommand(cli) cmd := newKeyLoadCommand(cli)
cmd.SetArgs(tc.args) cmd.SetArgs(tc.args)
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
assert.ErrorContains(t, cmd.Execute(), tc.expectedError) assert.ErrorContains(t, cmd.Execute(), tc.expectedError)
assert.Check(t, is.Contains(cli.OutBuffer().String(), tc.expectedOutput)) assert.Check(t, is.Contains(cli.OutBuffer().String(), tc.expectedOutput))
} }
@ -125,17 +122,12 @@ func TestLoadKeyFromPath(t *testing.T) {
} }
func testLoadKeyFromPath(t *testing.T, privKeyID string, privKeyFixture []byte) { func testLoadKeyFromPath(t *testing.T, privKeyID string, privKeyFixture []byte) {
privKeyDir, err := ioutil.TempDir("", "key-load-test-") privKeyFilepath := filepath.Join(t.TempDir(), "privkey.pem")
assert.NilError(t, err) assert.NilError(t, os.WriteFile(privKeyFilepath, privKeyFixture, notary.PrivNoExecPerms))
defer os.RemoveAll(privKeyDir)
privKeyFilepath := filepath.Join(privKeyDir, "privkey.pem")
assert.NilError(t, ioutil.WriteFile(privKeyFilepath, privKeyFixture, notary.PrivNoExecPerms))
keyStorageDir, err := ioutil.TempDir("", "loaded-keys-") keyStorageDir := t.TempDir()
assert.NilError(t, err)
defer os.RemoveAll(keyStorageDir)
passwd := "password" const passwd = "password"
cannedPasswordRetriever := passphrase.ConstantRetriever(passwd) cannedPasswordRetriever := passphrase.ConstantRetriever(passwd)
keyFileStore, err := storage.NewPrivateKeyFileStorage(keyStorageDir, notary.KeyExtension) keyFileStore, err := storage.NewPrivateKeyFileStorage(keyStorageDir, notary.KeyExtension)
assert.NilError(t, err) assert.NilError(t, err)
@ -156,7 +148,7 @@ func testLoadKeyFromPath(t *testing.T, privKeyID string, privKeyFixture []byte)
// verify the key content // verify the key content
from, _ := os.OpenFile(expectedImportKeyPath, os.O_RDONLY, notary.PrivExecPerms) from, _ := os.OpenFile(expectedImportKeyPath, os.O_RDONLY, notary.PrivExecPerms)
defer from.Close() defer from.Close()
fromBytes, _ := ioutil.ReadAll(from) fromBytes, _ := io.ReadAll(from)
keyPEM, _ := pem.Decode(fromBytes) keyPEM, _ := pem.Decode(fromBytes)
assert.Check(t, is.Equal("signer-name", keyPEM.Headers["role"])) assert.Check(t, is.Equal("signer-name", keyPEM.Headers["role"]))
// the default GUN is empty // the default GUN is empty
@ -181,43 +173,37 @@ func TestLoadKeyTooPermissive(t *testing.T) {
} }
func testLoadKeyTooPermissive(t *testing.T, privKeyFixture []byte) { func testLoadKeyTooPermissive(t *testing.T, privKeyFixture []byte) {
privKeyDir, err := ioutil.TempDir("", "key-load-test-") privKeyDir := t.TempDir()
assert.NilError(t, err)
defer os.RemoveAll(privKeyDir)
privKeyFilepath := filepath.Join(privKeyDir, "privkey477.pem") privKeyFilepath := filepath.Join(privKeyDir, "privkey477.pem")
assert.NilError(t, ioutil.WriteFile(privKeyFilepath, privKeyFixture, 0477)) assert.NilError(t, os.WriteFile(privKeyFilepath, privKeyFixture, 0477))
keyStorageDir, err := ioutil.TempDir("", "loaded-keys-")
assert.NilError(t, err)
defer os.RemoveAll(keyStorageDir)
// import the key to our keyStorageDir // import the key to our keyStorageDir
_, err = getPrivKeyBytesFromPath(privKeyFilepath) _, err := getPrivKeyBytesFromPath(privKeyFilepath)
expected := fmt.Sprintf("private key file %s must not be readable or writable by others", privKeyFilepath) expected := fmt.Sprintf("private key file %s must not be readable or writable by others", privKeyFilepath)
assert.Error(t, err, expected) assert.Error(t, err, expected)
privKeyFilepath = filepath.Join(privKeyDir, "privkey667.pem") privKeyFilepath = filepath.Join(privKeyDir, "privkey667.pem")
assert.NilError(t, ioutil.WriteFile(privKeyFilepath, privKeyFixture, 0677)) assert.NilError(t, os.WriteFile(privKeyFilepath, privKeyFixture, 0677))
_, err = getPrivKeyBytesFromPath(privKeyFilepath) _, err = getPrivKeyBytesFromPath(privKeyFilepath)
expected = fmt.Sprintf("private key file %s must not be readable or writable by others", privKeyFilepath) expected = fmt.Sprintf("private key file %s must not be readable or writable by others", privKeyFilepath)
assert.Error(t, err, expected) assert.Error(t, err, expected)
privKeyFilepath = filepath.Join(privKeyDir, "privkey777.pem") privKeyFilepath = filepath.Join(privKeyDir, "privkey777.pem")
assert.NilError(t, ioutil.WriteFile(privKeyFilepath, privKeyFixture, 0777)) assert.NilError(t, os.WriteFile(privKeyFilepath, privKeyFixture, 0777))
_, err = getPrivKeyBytesFromPath(privKeyFilepath) _, err = getPrivKeyBytesFromPath(privKeyFilepath)
expected = fmt.Sprintf("private key file %s must not be readable or writable by others", privKeyFilepath) expected = fmt.Sprintf("private key file %s must not be readable or writable by others", privKeyFilepath)
assert.Error(t, err, expected) assert.Error(t, err, expected)
privKeyFilepath = filepath.Join(privKeyDir, "privkey400.pem") privKeyFilepath = filepath.Join(privKeyDir, "privkey400.pem")
assert.NilError(t, ioutil.WriteFile(privKeyFilepath, privKeyFixture, 0400)) assert.NilError(t, os.WriteFile(privKeyFilepath, privKeyFixture, 0400))
_, err = getPrivKeyBytesFromPath(privKeyFilepath) _, err = getPrivKeyBytesFromPath(privKeyFilepath)
assert.NilError(t, err) assert.NilError(t, err)
privKeyFilepath = filepath.Join(privKeyDir, "privkey600.pem") privKeyFilepath = filepath.Join(privKeyDir, "privkey600.pem")
assert.NilError(t, ioutil.WriteFile(privKeyFilepath, privKeyFixture, 0600)) assert.NilError(t, os.WriteFile(privKeyFilepath, privKeyFixture, 0600))
_, err = getPrivKeyBytesFromPath(privKeyFilepath) _, err = getPrivKeyBytesFromPath(privKeyFilepath)
assert.NilError(t, err) assert.NilError(t, err)
@ -230,16 +216,12 @@ H3nzy2O6Q/ct4BjOBKa+WCdRtPo78bA+C/7t81ADQO8Jqaj59W50rwoqDQ==
func TestLoadPubKeyFailure(t *testing.T) { func TestLoadPubKeyFailure(t *testing.T) {
skip.If(t, runtime.GOOS == "windows") skip.If(t, runtime.GOOS == "windows")
pubKeyDir, err := ioutil.TempDir("", "key-load-test-pubkey-") pubKeyDir := t.TempDir()
assert.NilError(t, err)
defer os.RemoveAll(pubKeyDir)
pubKeyFilepath := filepath.Join(pubKeyDir, "pubkey.pem") pubKeyFilepath := filepath.Join(pubKeyDir, "pubkey.pem")
assert.NilError(t, ioutil.WriteFile(pubKeyFilepath, pubKeyFixture, notary.PrivNoExecPerms)) assert.NilError(t, os.WriteFile(pubKeyFilepath, pubKeyFixture, notary.PrivNoExecPerms))
keyStorageDir, err := ioutil.TempDir("", "loaded-keys-") keyStorageDir := t.TempDir()
assert.NilError(t, err)
defer os.RemoveAll(keyStorageDir)
passwd := "password" const passwd = "password"
cannedPasswordRetriever := passphrase.ConstantRetriever(passwd) cannedPasswordRetriever := passphrase.ConstantRetriever(passwd)
keyFileStore, err := storage.NewPrivateKeyFileStorage(keyStorageDir, notary.KeyExtension) keyFileStore, err := storage.NewPrivateKeyFileStorage(keyStorageDir, notary.KeyExtension)
assert.NilError(t, err) assert.NilError(t, err)

View File

@ -1,8 +1,7 @@
package trust package trust
import ( import (
"io/ioutil" "io"
"os"
"testing" "testing"
"github.com/docker/cli/cli/trust" "github.com/docker/cli/cli/trust"
@ -50,7 +49,7 @@ func TestTrustRevokeCommandErrors(t *testing.T) {
cmd := newRevokeCommand( cmd := newRevokeCommand(
test.NewFakeCli(&fakeClient{})) test.NewFakeCli(&fakeClient{}))
cmd.SetArgs(tc.args) cmd.SetArgs(tc.args)
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
assert.ErrorContains(t, cmd.Execute(), tc.expectedError) assert.ErrorContains(t, cmd.Execute(), tc.expectedError)
} }
} }
@ -131,7 +130,7 @@ func TestTrustRevokeCommand(t *testing.T) {
cli.SetNotaryClient(tc.notaryRepository) cli.SetNotaryClient(tc.notaryRepository)
cmd := newRevokeCommand(cli) cmd := newRevokeCommand(cli)
cmd.SetArgs(tc.args) cmd.SetArgs(tc.args)
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
if tc.expectedErr != "" { if tc.expectedErr != "" {
assert.ErrorContains(t, cmd.Execute(), tc.expectedErr) assert.ErrorContains(t, cmd.Execute(), tc.expectedErr)
return return
@ -144,11 +143,7 @@ func TestTrustRevokeCommand(t *testing.T) {
} }
func TestGetSignableRolesForTargetAndRemoveError(t *testing.T) { func TestGetSignableRolesForTargetAndRemoveError(t *testing.T) {
tmpDir, err := ioutil.TempDir("", "notary-test-") notaryRepo, err := client.NewFileCachedRepository(t.TempDir(), "gun", "https://localhost", nil, passphrase.ConstantRetriever("password"), trustpinning.TrustPinConfig{})
assert.NilError(t, err)
defer os.RemoveAll(tmpDir)
notaryRepo, err := client.NewFileCachedRepository(tmpDir, "gun", "https://localhost", nil, passphrase.ConstantRetriever("password"), trustpinning.TrustPinConfig{})
assert.NilError(t, err) assert.NilError(t, err)
target := client.Target{} target := client.Target{}
err = getSignableRolesForTargetAndRemove(target, notaryRepo) err = getSignableRolesForTargetAndRemove(target, notaryRepo)

View File

@ -3,8 +3,7 @@ package trust
import ( import (
"bytes" "bytes"
"encoding/json" "encoding/json"
"io/ioutil" "io"
"os"
"runtime" "runtime"
"testing" "testing"
@ -62,15 +61,12 @@ func TestTrustSignCommandErrors(t *testing.T) {
}, },
} }
// change to a tmpdir // change to a tmpdir
tmpDir, err := ioutil.TempDir("", "docker-sign-test-") config.SetDir(t.TempDir())
assert.NilError(t, err)
defer os.RemoveAll(tmpDir)
config.SetDir(tmpDir)
for _, tc := range testCases { for _, tc := range testCases {
cmd := newSignCommand( cmd := newSignCommand(
test.NewFakeCli(&fakeClient{})) test.NewFakeCli(&fakeClient{}))
cmd.SetArgs(tc.args) cmd.SetArgs(tc.args)
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
assert.ErrorContains(t, cmd.Execute(), tc.expectedError) assert.ErrorContains(t, cmd.Execute(), tc.expectedError)
} }
} }
@ -80,16 +76,12 @@ func TestTrustSignCommandOfflineErrors(t *testing.T) {
cli.SetNotaryClient(notaryfake.GetOfflineNotaryRepository) cli.SetNotaryClient(notaryfake.GetOfflineNotaryRepository)
cmd := newSignCommand(cli) cmd := newSignCommand(cli)
cmd.SetArgs([]string{"reg-name.io/image:tag"}) cmd.SetArgs([]string{"reg-name.io/image:tag"})
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
assert.ErrorContains(t, cmd.Execute(), "client is offline") assert.ErrorContains(t, cmd.Execute(), "client is offline")
} }
func TestGetOrGenerateNotaryKey(t *testing.T) { func TestGetOrGenerateNotaryKey(t *testing.T) {
tmpDir, err := ioutil.TempDir("", "notary-test-") notaryRepo, err := client.NewFileCachedRepository(t.TempDir(), "gun", "https://localhost", nil, passphrase.ConstantRetriever(passwd), trustpinning.TrustPinConfig{})
assert.NilError(t, err)
defer os.RemoveAll(tmpDir)
notaryRepo, err := client.NewFileCachedRepository(tmpDir, "gun", "https://localhost", nil, passphrase.ConstantRetriever(passwd), trustpinning.TrustPinConfig{})
assert.NilError(t, err) assert.NilError(t, err)
// repo is empty, try making a root key // repo is empty, try making a root key
@ -131,11 +123,8 @@ func TestGetOrGenerateNotaryKey(t *testing.T) {
func TestAddStageSigners(t *testing.T) { func TestAddStageSigners(t *testing.T) {
skip.If(t, runtime.GOOS == "windows", "FIXME: not supported currently") skip.If(t, runtime.GOOS == "windows", "FIXME: not supported currently")
tmpDir, err := ioutil.TempDir("", "notary-test-")
assert.NilError(t, err)
defer os.RemoveAll(tmpDir)
notaryRepo, err := client.NewFileCachedRepository(tmpDir, "gun", "https://localhost", nil, passphrase.ConstantRetriever(passwd), trustpinning.TrustPinConfig{}) notaryRepo, err := client.NewFileCachedRepository(t.TempDir(), "gun", "https://localhost", nil, passphrase.ConstantRetriever(passwd), trustpinning.TrustPinConfig{})
assert.NilError(t, err) assert.NilError(t, err)
// stage targets/user // stage targets/user
@ -216,11 +205,7 @@ func TestAddStageSigners(t *testing.T) {
} }
func TestGetSignedManifestHashAndSize(t *testing.T) { func TestGetSignedManifestHashAndSize(t *testing.T) {
tmpDir, err := ioutil.TempDir("", "notary-test-") notaryRepo, err := client.NewFileCachedRepository(t.TempDir(), "gun", "https://localhost", nil, passphrase.ConstantRetriever(passwd), trustpinning.TrustPinConfig{})
assert.NilError(t, err)
defer os.RemoveAll(tmpDir)
notaryRepo, err := client.NewFileCachedRepository(tmpDir, "gun", "https://localhost", nil, passphrase.ConstantRetriever(passwd), trustpinning.TrustPinConfig{})
assert.NilError(t, err) assert.NilError(t, err)
target := &client.Target{} target := &client.Target{}
target.Hashes, target.Length, err = getSignedManifestHashAndSize(notaryRepo, "test") target.Hashes, target.Length, err = getSignedManifestHashAndSize(notaryRepo, "test")
@ -244,11 +229,7 @@ func TestGetReleasedTargetHashAndSize(t *testing.T) {
} }
func TestCreateTarget(t *testing.T) { func TestCreateTarget(t *testing.T) {
tmpDir, err := ioutil.TempDir("", "notary-test-") notaryRepo, err := client.NewFileCachedRepository(t.TempDir(), "gun", "https://localhost", nil, passphrase.ConstantRetriever(passwd), trustpinning.TrustPinConfig{})
assert.NilError(t, err)
defer os.RemoveAll(tmpDir)
notaryRepo, err := client.NewFileCachedRepository(tmpDir, "gun", "https://localhost", nil, passphrase.ConstantRetriever(passwd), trustpinning.TrustPinConfig{})
assert.NilError(t, err) assert.NilError(t, err)
_, err = createTarget(notaryRepo, "") _, err = createTarget(notaryRepo, "")
assert.Error(t, err, "No tag specified") assert.Error(t, err, "No tag specified")
@ -257,11 +238,7 @@ func TestCreateTarget(t *testing.T) {
} }
func TestGetExistingSignatureInfoForReleasedTag(t *testing.T) { func TestGetExistingSignatureInfoForReleasedTag(t *testing.T) {
tmpDir, err := ioutil.TempDir("", "notary-test-") notaryRepo, err := client.NewFileCachedRepository(t.TempDir(), "gun", "https://localhost", nil, passphrase.ConstantRetriever(passwd), trustpinning.TrustPinConfig{})
assert.NilError(t, err)
defer os.RemoveAll(tmpDir)
notaryRepo, err := client.NewFileCachedRepository(tmpDir, "gun", "https://localhost", nil, passphrase.ConstantRetriever(passwd), trustpinning.TrustPinConfig{})
assert.NilError(t, err) assert.NilError(t, err)
_, err = getExistingSignatureInfoForReleasedTag(notaryRepo, "test") _, err = getExistingSignatureInfoForReleasedTag(notaryRepo, "test")
assert.Error(t, err, "client is offline") assert.Error(t, err, "client is offline")
@ -277,18 +254,16 @@ func TestPrettyPrintExistingSignatureInfo(t *testing.T) {
} }
func TestSignCommandChangeListIsCleanedOnError(t *testing.T) { func TestSignCommandChangeListIsCleanedOnError(t *testing.T) {
tmpDir, err := ioutil.TempDir("", "docker-sign-test-") tmpDir := t.TempDir()
assert.NilError(t, err)
defer os.RemoveAll(tmpDir)
config.SetDir(tmpDir) config.SetDir(tmpDir)
cli := test.NewFakeCli(&fakeClient{}) cli := test.NewFakeCli(&fakeClient{})
cli.SetNotaryClient(notaryfake.GetLoadedNotaryRepository) cli.SetNotaryClient(notaryfake.GetLoadedNotaryRepository)
cmd := newSignCommand(cli) cmd := newSignCommand(cli)
cmd.SetArgs([]string{"ubuntu:latest"}) cmd.SetArgs([]string{"ubuntu:latest"})
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
err = cmd.Execute() err := cmd.Execute()
assert.Assert(t, err != nil) assert.Assert(t, err != nil)
notaryRepo, err := client.NewFileCachedRepository(tmpDir, "docker.io/library/ubuntu", "https://localhost", nil, passphrase.ConstantRetriever(passwd), trustpinning.TrustPinConfig{}) notaryRepo, err := client.NewFileCachedRepository(tmpDir, "docker.io/library/ubuntu", "https://localhost", nil, passphrase.ConstantRetriever(passwd), trustpinning.TrustPinConfig{})
@ -303,7 +278,7 @@ func TestSignCommandLocalFlag(t *testing.T) {
cli.SetNotaryClient(notaryfake.GetEmptyTargetsNotaryRepository) cli.SetNotaryClient(notaryfake.GetEmptyTargetsNotaryRepository)
cmd := newSignCommand(cli) cmd := newSignCommand(cli)
cmd.SetArgs([]string{"--local", "reg-name.io/image:red"}) cmd.SetArgs([]string{"--local", "reg-name.io/image:red"})
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
assert.ErrorContains(t, cmd.Execute(), "error contacting notary server: dial tcp: lookup reg-name.io") assert.ErrorContains(t, cmd.Execute(), "error contacting notary server: dial tcp: lookup reg-name.io")
} }

View File

@ -4,7 +4,6 @@ import (
"context" "context"
"fmt" "fmt"
"io" "io"
"io/ioutil"
"os" "os"
"path" "path"
"regexp" "regexp"
@ -125,7 +124,7 @@ func ingestPublicKeys(pubKeyPaths []string) ([]data.PublicKey, error) {
defer pubKeyFile.Close() defer pubKeyFile.Close()
// limit to // limit to
l := io.LimitReader(pubKeyFile, 1<<20) l := io.LimitReader(pubKeyFile, 1<<20)
pubKeyBytes, err := ioutil.ReadAll(l) pubKeyBytes, err := io.ReadAll(l)
if err != nil { if err != nil {
return nil, errors.Wrap(err, "unable to read public key from file") return nil, errors.Wrap(err, "unable to read public key from file")
} }

View File

@ -2,7 +2,7 @@ package trust
import ( import (
"fmt" "fmt"
"io/ioutil" "io"
"os" "os"
"path/filepath" "path/filepath"
"runtime" "runtime"
@ -52,29 +52,24 @@ func TestTrustSignerAddErrors(t *testing.T) {
expectedError: "signer name \"_alice\" must start with lowercase alphanumeric characters and can include \"-\" or \"_\" after the first character", expectedError: "signer name \"_alice\" must start with lowercase alphanumeric characters and can include \"-\" or \"_\" after the first character",
}, },
} }
tmpDir, err := ioutil.TempDir("", "docker-sign-test-") config.SetDir(t.TempDir())
assert.NilError(t, err)
defer os.RemoveAll(tmpDir)
config.SetDir(tmpDir)
for _, tc := range testCases { for _, tc := range testCases {
cli := test.NewFakeCli(&fakeClient{}) cli := test.NewFakeCli(&fakeClient{})
cli.SetNotaryClient(notaryfake.GetOfflineNotaryRepository) cli.SetNotaryClient(notaryfake.GetOfflineNotaryRepository)
cmd := newSignerAddCommand(cli) cmd := newSignerAddCommand(cli)
cmd.SetArgs(tc.args) cmd.SetArgs(tc.args)
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
assert.ErrorContains(t, cmd.Execute(), tc.expectedError) assert.ErrorContains(t, cmd.Execute(), tc.expectedError)
} }
} }
func TestSignerAddCommandNoTargetsKey(t *testing.T) { func TestSignerAddCommandNoTargetsKey(t *testing.T) {
tmpDir, err := ioutil.TempDir("", "docker-sign-test-") config.SetDir(t.TempDir())
assert.NilError(t, err)
defer os.RemoveAll(tmpDir)
config.SetDir(tmpDir)
tmpfile, err := ioutil.TempFile("", "pemfile") tmpfile, err := os.CreateTemp("", "pemfile")
assert.NilError(t, err) assert.NilError(t, err)
tmpfile.Close()
defer os.Remove(tmpfile.Name()) defer os.Remove(tmpfile.Name())
cli := test.NewFakeCli(&fakeClient{}) cli := test.NewFakeCli(&fakeClient{})
@ -82,22 +77,19 @@ func TestSignerAddCommandNoTargetsKey(t *testing.T) {
cmd := newSignerAddCommand(cli) cmd := newSignerAddCommand(cli)
cmd.SetArgs([]string{"--key", tmpfile.Name(), "alice", "alpine", "linuxkit/alpine"}) cmd.SetArgs([]string{"--key", tmpfile.Name(), "alice", "alpine", "linuxkit/alpine"})
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
assert.Error(t, cmd.Execute(), fmt.Sprintf("could not parse public key from file: %s: no valid public key found", tmpfile.Name())) assert.Error(t, cmd.Execute(), fmt.Sprintf("could not parse public key from file: %s: no valid public key found", tmpfile.Name()))
} }
func TestSignerAddCommandBadKeyPath(t *testing.T) { func TestSignerAddCommandBadKeyPath(t *testing.T) {
tmpDir, err := ioutil.TempDir("", "docker-sign-test-") config.SetDir(t.TempDir())
assert.NilError(t, err)
defer os.RemoveAll(tmpDir)
config.SetDir(tmpDir)
cli := test.NewFakeCli(&fakeClient{}) cli := test.NewFakeCli(&fakeClient{})
cli.SetNotaryClient(notaryfake.GetEmptyTargetsNotaryRepository) cli.SetNotaryClient(notaryfake.GetEmptyTargetsNotaryRepository)
cmd := newSignerAddCommand(cli) cmd := newSignerAddCommand(cli)
cmd.SetArgs([]string{"--key", "/path/to/key.pem", "alice", "alpine"}) cmd.SetArgs([]string{"--key", "/path/to/key.pem", "alice", "alpine"})
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
expectedError := "unable to read public key from file: open /path/to/key.pem: no such file or directory" expectedError := "unable to read public key from file: open /path/to/key.pem: no such file or directory"
if runtime.GOOS == "windows" { if runtime.GOOS == "windows" {
expectedError = "unable to read public key from file: open /path/to/key.pem: The system cannot find the path specified." expectedError = "unable to read public key from file: open /path/to/key.pem: The system cannot find the path specified."
@ -106,16 +98,11 @@ func TestSignerAddCommandBadKeyPath(t *testing.T) {
} }
func TestSignerAddCommandInvalidRepoName(t *testing.T) { func TestSignerAddCommandInvalidRepoName(t *testing.T) {
tmpDir, err := ioutil.TempDir("", "docker-sign-test-") config.SetDir(t.TempDir())
assert.NilError(t, err)
defer os.RemoveAll(tmpDir)
config.SetDir(tmpDir)
pubKeyDir, err := ioutil.TempDir("", "key-load-test-pubkey-") pubKeyDir := t.TempDir()
assert.NilError(t, err)
defer os.RemoveAll(pubKeyDir)
pubKeyFilepath := filepath.Join(pubKeyDir, "pubkey.pem") pubKeyFilepath := filepath.Join(pubKeyDir, "pubkey.pem")
assert.NilError(t, ioutil.WriteFile(pubKeyFilepath, pubKeyFixture, notary.PrivNoExecPerms)) assert.NilError(t, os.WriteFile(pubKeyFilepath, pubKeyFixture, notary.PrivNoExecPerms))
cli := test.NewFakeCli(&fakeClient{}) cli := test.NewFakeCli(&fakeClient{})
cli.SetNotaryClient(notaryfake.GetUninitializedNotaryRepository) cli.SetNotaryClient(notaryfake.GetUninitializedNotaryRepository)
@ -123,7 +110,7 @@ func TestSignerAddCommandInvalidRepoName(t *testing.T) {
imageName := "870d292919d01a0af7e7f056271dc78792c05f55f49b9b9012b6d89725bd9abd" imageName := "870d292919d01a0af7e7f056271dc78792c05f55f49b9b9012b6d89725bd9abd"
cmd.SetArgs([]string{"--key", pubKeyFilepath, "alice", imageName}) cmd.SetArgs([]string{"--key", pubKeyFilepath, "alice", imageName})
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
assert.Error(t, cmd.Execute(), "Failed to add signer to: 870d292919d01a0af7e7f056271dc78792c05f55f49b9b9012b6d89725bd9abd") assert.Error(t, cmd.Execute(), "Failed to add signer to: 870d292919d01a0af7e7f056271dc78792c05f55f49b9b9012b6d89725bd9abd")
expectedErr := fmt.Sprintf("invalid repository name (%s), cannot specify 64-byte hexadecimal strings\n\n", imageName) expectedErr := fmt.Sprintf("invalid repository name (%s), cannot specify 64-byte hexadecimal strings\n\n", imageName)
@ -139,8 +126,9 @@ func TestIngestPublicKeys(t *testing.T) {
} }
assert.Error(t, err, expectedError) assert.Error(t, err, expectedError)
// Call with real file path // Call with real file path
tmpfile, err := ioutil.TempFile("", "pemfile") tmpfile, err := os.CreateTemp("", "pemfile")
assert.NilError(t, err) assert.NilError(t, err)
tmpfile.Close()
defer os.Remove(tmpfile.Name()) defer os.Remove(tmpfile.Name())
_, err = ingestPublicKeys([]string{tmpfile.Name()}) _, err = ingestPublicKeys([]string{tmpfile.Name()})
assert.Error(t, err, fmt.Sprintf("could not parse public key from file: %s: no valid public key found", tmpfile.Name())) assert.Error(t, err, fmt.Sprintf("could not parse public key from file: %s: no valid public key found", tmpfile.Name()))

View File

@ -1,7 +1,7 @@
package trust package trust
import ( import (
"io/ioutil" "io"
"testing" "testing"
"github.com/docker/cli/internal/test" "github.com/docker/cli/internal/test"
@ -32,7 +32,7 @@ func TestTrustSignerRemoveErrors(t *testing.T) {
cmd := newSignerRemoveCommand( cmd := newSignerRemoveCommand(
test.NewFakeCli(&fakeClient{})) test.NewFakeCli(&fakeClient{}))
cmd.SetArgs(tc.args) cmd.SetArgs(tc.args)
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
assert.ErrorContains(t, cmd.Execute(), tc.expectedError) assert.ErrorContains(t, cmd.Execute(), tc.expectedError)
} }
testCasesWithOutput := []struct { testCasesWithOutput := []struct {
@ -61,7 +61,7 @@ func TestTrustSignerRemoveErrors(t *testing.T) {
cli.SetNotaryClient(notaryfake.GetOfflineNotaryRepository) cli.SetNotaryClient(notaryfake.GetOfflineNotaryRepository)
cmd := newSignerRemoveCommand(cli) cmd := newSignerRemoveCommand(cli)
cmd.SetArgs(tc.args) cmd.SetArgs(tc.args)
cmd.SetOut(ioutil.Discard) cmd.SetOut(io.Discard)
cmd.Execute() cmd.Execute()
assert.Check(t, is.Contains(cli.ErrBuffer().String(), tc.expectedError)) assert.Check(t, is.Contains(cli.ErrBuffer().String(), tc.expectedError))
} }