github.com/ubuntu-core/snappy@v0.0.0-20210827154228-9e584df982bb/cmd/snap/keymgr_test.go (about) 1 // -*- Mode: Go; indent-tabs-mode: t -*- 2 3 /* 4 * Copyright (C) 2021 Canonical Ltd 5 * 6 * This program is free software: you can redistribute it and/or modify 7 * it under the terms of the GNU General Public License version 3 as 8 * published by the Free Software Foundation. 9 * 10 * This program is distributed in the hope that it will be useful, 11 * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 * GNU General Public License for more details. 14 * 15 * You should have received a copy of the GNU General Public License 16 * along with this program. If not, see <http://www.gnu.org/licenses/>. 17 * 18 */ 19 20 package main_test 21 22 import ( 23 "os" 24 25 "gopkg.in/check.v1" 26 27 "github.com/snapcore/snapd/asserts" 28 snap "github.com/snapcore/snapd/cmd/snap" 29 "github.com/snapcore/snapd/testutil" 30 ) 31 32 type keymgrSuite struct{} 33 34 var _ = check.Suite(&keymgrSuite{}) 35 36 func (keymgrSuite) TestGPGKeypairManager(c *check.C) { 37 keypairMgr, err := snap.GetKeypairManager() 38 c.Check(err, check.IsNil) 39 c.Check(keypairMgr, check.FitsTypeOf, &asserts.GPGKeypairManager{}) 40 } 41 42 func mockNopExtKeyMgr(c *check.C) (pgm *testutil.MockCmd, restore func()) { 43 os.Setenv("SNAPD_EXT_KEYMGR", "keymgr") 44 pgm = testutil.MockCommand(c, "keymgr", ` 45 if [ "$1" == "features" ]; then 46 echo '{"signing":["RSA-PKCS"] , "public-keys":["DER"]}' 47 exit 0 48 fi 49 exit 1 50 `) 51 r := func() { 52 pgm.Restore() 53 os.Unsetenv("SNAPD_EXT_KEYMGR") 54 } 55 56 return pgm, r 57 } 58 59 func (keymgrSuite) TestExternalKeypairManager(c *check.C) { 60 pgm, restore := mockNopExtKeyMgr(c) 61 defer restore() 62 63 keypairMgr, err := snap.GetKeypairManager() 64 c.Check(err, check.IsNil) 65 c.Check(keypairMgr, check.FitsTypeOf, &asserts.ExternalKeypairManager{}) 66 c.Check(pgm.Calls(), check.HasLen, 1) 67 } 68 69 func (keymgrSuite) TestExternalKeypairManagerError(c *check.C) { 70 os.Setenv("SNAPD_EXT_KEYMGR", "keymgr") 71 defer os.Unsetenv("SNAPD_EXT_KEYMGR") 72 73 pgm := testutil.MockCommand(c, "keymgr", ` 74 exit 1 75 `) 76 defer pgm.Restore() 77 78 _, err := snap.GetKeypairManager() 79 c.Check(err, check.ErrorMatches, `cannot setup external keypair manager: external keypair manager "keymgr" \[features\] failed: exit status 1.*`) 80 } 81 82 func (keymgrSuite) TestExternalKeypairManagerGenerateKey(c *check.C) { 83 _, restore := mockNopExtKeyMgr(c) 84 defer restore() 85 86 keypairMgr, err := snap.GetKeypairManager() 87 c.Check(err, check.IsNil) 88 89 err = snap.GenerateKey(keypairMgr, "key") 90 c.Check(err, check.ErrorMatches, `cannot generate external keypair manager key via snap command, use the appropriate external procedure to create a 4096-bit RSA key under the name/label "key"`) 91 }