github.com/cloudbase/juju-core@v0.0.0-20140504232958-a7271ac7912f/upgrades/systemsshkey_test.go (about) 1 // Copyright 2014 Canonical Ltd. 2 // Licensed under the AGPLv3, see LICENCE file for details. 3 4 package upgrades_test 5 6 import ( 7 "io/ioutil" 8 "os" 9 "path/filepath" 10 11 gc "launchpad.net/gocheck" 12 13 jujutesting "launchpad.net/juju-core/juju/testing" 14 "launchpad.net/juju-core/state" 15 jc "launchpad.net/juju-core/testing/checkers" 16 "launchpad.net/juju-core/upgrades" 17 "launchpad.net/juju-core/utils/ssh" 18 ) 19 20 type systemSSHKeySuite struct { 21 jujutesting.JujuConnSuite 22 ctx upgrades.Context 23 } 24 25 var _ = gc.Suite(&systemSSHKeySuite{}) 26 27 func (s *systemSSHKeySuite) SetUpTest(c *gc.C) { 28 s.JujuConnSuite.SetUpTest(c) 29 apiState, _ := s.OpenAPIAsNewMachine(c, state.JobManageEnviron) 30 s.ctx = &mockContext{ 31 agentConfig: &mockAgentConfig{dataDir: s.DataDir()}, 32 apiState: apiState, 33 } 34 _, err := os.Stat(s.keyFile()) 35 c.Assert(err, jc.Satisfies, os.IsNotExist) 36 // There's initially one authorised key for the test user. 37 cfg, err := s.State.EnvironConfig() 38 c.Assert(err, gc.IsNil) 39 authKeys := ssh.SplitAuthorisedKeys(cfg.AuthorizedKeys()) 40 c.Assert(authKeys, gc.HasLen, 1) 41 } 42 43 func (s *systemSSHKeySuite) keyFile() string { 44 return filepath.Join(s.DataDir(), "system-identity") 45 } 46 47 func (s *systemSSHKeySuite) assertKeyCreation(c *gc.C) { 48 c.Assert(s.keyFile(), jc.IsNonEmptyFile) 49 50 // Check the private key from the system identify file. 51 privateKey, err := ioutil.ReadFile(s.keyFile()) 52 c.Assert(err, gc.IsNil) 53 c.Check(string(privateKey), jc.HasPrefix, "-----BEGIN RSA PRIVATE KEY-----\n") 54 c.Check(string(privateKey), jc.HasSuffix, "-----END RSA PRIVATE KEY-----\n") 55 56 // Check the public key from the auth keys config. 57 cfg, err := s.JujuConnSuite.State.EnvironConfig() 58 c.Assert(err, gc.IsNil) 59 authKeys := ssh.SplitAuthorisedKeys(cfg.AuthorizedKeys()) 60 // The dummy env is created with 1 fake key. We check that another has been added. 61 c.Assert(authKeys, gc.HasLen, 2) 62 c.Check(authKeys[1], jc.HasPrefix, "ssh-rsa ") 63 c.Check(authKeys[1], jc.HasSuffix, " juju-system-key") 64 } 65 66 func (s *systemSSHKeySuite) TestSystemKeyCreated(c *gc.C) { 67 err := upgrades.EnsureSystemSSHKey(s.ctx) 68 c.Assert(err, gc.IsNil) 69 s.assertKeyCreation(c) 70 } 71 72 func (s *systemSSHKeySuite) TestIdempotent(c *gc.C) { 73 err := upgrades.EnsureSystemSSHKey(s.ctx) 74 c.Assert(err, gc.IsNil) 75 76 privateKey, err := ioutil.ReadFile(s.keyFile()) 77 c.Assert(err, gc.IsNil) 78 79 err = upgrades.EnsureSystemSSHKey(s.ctx) 80 c.Assert(err, gc.IsNil) 81 82 // Ensure we haven't generated the key again a second time. 83 privateKey2, err := ioutil.ReadFile(s.keyFile()) 84 c.Assert(err, gc.IsNil) 85 c.Assert(privateKey, gc.DeepEquals, privateKey2) 86 }