<commit_before>/*
Copyright 2016 Gravitational, Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package client

import (
	//log "github.com/Sirupsen/logrus"
	"fmt"
	"os"
	"time"

	"github.com/gravitational/teleport/lib/auth/testauthority"
	"github.com/gravitational/teleport/lib/utils"
	"github.com/gravitational/trace"
	"golang.org/x/crypto/ssh"
	"gopkg.in/check.v1"
)

type KeyStoreTestSuite struct {
	storeDir string
	store    *FSLocalKeyStore
	keygen   *testauthority.Keygen
}

var _ = check.Suite(&KeyStoreTestSuite{})

func (s *KeyStoreTestSuite) SetUpSuite(c *check.C) {
	utils.InitLoggerForTests()
	var err error
	s.keygen = testauthority.New()
	s.storeDir = c.MkDir()
	s.store, err = NewFSLocalKeyStore(s.storeDir)
	c.Assert(err, check.IsNil)
	c.Assert(s.store, check.NotNil)
	c.Assert(utils.IsDir(s.store.KeyDir), check.Equals, true)
}

func (s *KeyStoreTestSuite) TearDownSuite(c *check.C) {
	os.RemoveAll(s.storeDir)
}

func (s *KeyStoreTestSuite) SetUpTest(c *check.C) {
	os.RemoveAll(s.store.KeyDir)
}

func (s *KeyStoreTestSuite) TestListKeys(c *check.C) {
	const keyNum = 5
	// add 5 keys for "bob"
	keys := make([]Key, keyNum)
	for i := 0; i < keyNum; i++ {
		key := s.makeSignedKey(c, false)
		s.store.AddKey(fmt.Sprintf("host-%v", i), "bob", key)
		keys[i] = *key
	}
	// add 1 key for "sam"
	samKey := s.makeSignedKey(c, false)
	s.store.AddKey("sam.host", "sam", samKey)

	// read all bob keys:
	keys2, err := s.store.GetKeys("bob")
	c.Assert(err, check.IsNil)
	c.Assert(keys2, check.HasLen, keyNum)
	c.Assert(keys2, check.DeepEquals, keys)

	// read sam's key and make sure it's the same:
	keys, err = s.store.GetKeys("sam")
	c.Assert(err, check.IsNil)
	c.Assert(keys, check.HasLen, 1)
	c.Assert(samKey.Cert, check.DeepEquals, keys[0].Cert)
	c.Assert(samKey.Pub, check.DeepEquals, keys[0].Pub)
}

func (s *KeyStoreTestSuite) TestKeyCRUD(c *check.C) {
	key := s.makeSignedKey(c, false)

	// add key:
	err := s.store.AddKey("host.a", "bob", key)
	c.Assert(err, check.IsNil)

	// load back and compare:
	keyCopy, err := s.store.GetKey("host.a", "bob")
	c.Assert(err, check.IsNil)
	c.Assert(key, check.DeepEquals, keyCopy)

	// Delete & verify that its' gone
	err = s.store.DeleteKey("host.a", "bob")
	c.Assert(err, check.IsNil)
	keyCopy, err = s.store.GetKey("host.a", "bob")
	c.Assert(err, check.NotNil)
	c.Assert(trace.IsNotFound(err), check.Equals, true)

	// Delete non-existing
	err = s.store.DeleteKey("non-existing-host", "non-existing-user")
	c.Assert(err, check.NotNil)
	c.Assert(trace.IsNotFound(err), check.Equals, true)
}

func (s *KeyStoreTestSuite) TestKeyExpiration(c *check.C) {
	// make two keys: one is current, and the expire one
	good := s.makeSignedKey(c, false)
	expired := s.makeSignedKey(c, true)

	s.store.AddKey("good.host", "sam", good)
	s.store.AddKey("expired.host", "sam", expired)

	// get all keys back. only "good" key should be returned:
	keys, _ := s.store.GetKeys("sam")
	c.Assert(keys, check.HasLen, 1)
	c.Assert(keys[0], check.DeepEquals, *good)
}

func (s *KeyStoreTestSuite) TestKnownHosts(c *check.C) {
	os.MkdirAll(s.store.KeyDir, 0777)
	pub, _, _, _, err := ssh.ParseAuthorizedKey(CAPub)
	c.Assert(err, check.IsNil)

	_, p2, _ := s.keygen.GenerateKeyPair("")
	pub2, _, _, _, _ := ssh.ParseAuthorizedKey(p2)

	err = s.store.AddKnownCA("example.com", []ssh.PublicKey{pub})
	c.Assert(err, check.IsNil)
	err = s.store.AddKnownCA("example.com", []ssh.PublicKey{pub2})
	c.Assert(err, check.IsNil)
	err = s.store.AddKnownCA("example.org", []ssh.PublicKey{pub2})
	c.Assert(err, check.IsNil)

	keys, err := s.store.GetKnownCAs()
	c.Assert(err, check.IsNil)
	c.Assert(keys, check.HasLen, 3)
	c.Assert(keys, check.DeepEquals, []ssh.PublicKey{pub, pub2, pub2})

	// check against dupes:
	before, _ := s.store.GetKnownCAs()
	s.store.AddKnownCA("example.org", []ssh.PublicKey{pub2})
	s.store.AddKnownCA("example.org", []ssh.PublicKey{pub2})
	after, _ := s.store.GetKnownCAs()
	c.Assert(len(before), check.Equals, len(after))
}

// makeSIgnedKey helper returns all 3 components of a user key (signed by CAPriv key)
func (s *KeyStoreTestSuite) makeSignedKey(c *check.C, makeExpired bool) *Key {
	var (
		err             error
		priv, pub, cert []byte
	)
	priv, pub, _ = s.keygen.GenerateKeyPair("")
	username := "vincento"
	allowedLogins := []string{username, "root"}<commit_msg>Updated tests<commit_after>/*
Copyright 2016 Gravitational, Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package client

import (
	//log "github.com/Sirupsen/logrus"
	"fmt"
	"os"
	"time"

	"github.com/gravitational/teleport/lib/auth/testauthority"
	"github.com/gravitational/teleport/lib/sshutils"
	"github.com/gravitational/teleport/lib/utils"
	"github.com/gravitational/trace"
	"golang.org/x/crypto/ssh"
	"gopkg.in/check.v1"
)

type KeyStoreTestSuite struct {
	storeDir string
	store    *FSLocalKeyStore
	keygen   *testauthority.Keygen
}

var _ = check.Suite(&KeyStoreTestSuite{})

func (s *KeyStoreTestSuite) SetUpSuite(c *check.C) {
	utils.InitLoggerForTests()
	var err error
	s.keygen = testauthority.New()
	s.storeDir = c.MkDir()
	s.store, err = NewFSLocalKeyStore(s.storeDir)
	c.Assert(err, check.IsNil)
	c.Assert(s.store, check.NotNil)
	c.Assert(utils.IsDir(s.store.KeyDir), check.Equals, true)
}

func (s *KeyStoreTestSuite) TearDownSuite(c *check.C) {
	os.RemoveAll(s.storeDir)
}

func (s *KeyStoreTestSuite) SetUpTest(c *check.C) {
	os.RemoveAll(s.store.KeyDir)
}

func (s *KeyStoreTestSuite) TestListKeys(c *check.C) {
	const keyNum = 5
	// add 5 keys for "bob"
	keys := make([]Key, keyNum)
	for i := 0; i < keyNum; i++ {
		key := s.makeSignedKey(c, false)
		s.store.AddKey(fmt.Sprintf("host-%v", i), "bob", key)
		keys[i] = *key
	}
	// add 1 key for "sam"
	samKey := s.makeSignedKey(c, false)
	s.store.AddKey("sam.host", "sam", samKey)

	// read all bob keys:
	keys2, err := s.store.GetKeys("bob")
	c.Assert(err, check.IsNil)
	c.Assert(keys2, check.HasLen, keyNum)
	c.Assert(keys2, check.DeepEquals, keys)

	// read sam's key and make sure it's the same:
	keys, err = s.store.GetKeys("sam")
	c.Assert(err, check.IsNil)
	c.Assert(keys, check.HasLen, 1)
	c.Assert(samKey.Cert, check.DeepEquals, keys[0].Cert)
	c.Assert(samKey.Pub, check.DeepEquals, keys[0].Pub)
}

func (s *KeyStoreTestSuite) TestKeyCRUD(c *check.C) {
	key := s.makeSignedKey(c, false)

	// add key:
	err := s.store.AddKey("host.a", "bob", key)
	c.Assert(err, check.IsNil)

	// load back and compare:
	keyCopy, err := s.store.GetKey("host.a", "bob")
	c.Assert(err, check.IsNil)
	c.Assert(key, check.DeepEquals, keyCopy)

	// Delete & verify that its' gone
	err = s.store.DeleteKey("host.a", "bob")
	c.Assert(err, check.IsNil)
	keyCopy, err = s.store.GetKey("host.a", "bob")
	c.Assert(err, check.NotNil)
	c.Assert(trace.IsNotFound(err), check.Equals, true)

	// Delete non-existing
	err = s.store.DeleteKey("non-existing-host", "non-existing-user")
	c.Assert(err, check.NotNil)
	c.Assert(trace.IsNotFound(err), check.Equals, true)
}

func (s *KeyStoreTestSuite) TestKeyExpiration(c *check.C) {
	// make two keys: one is current, and the expire one
	good := s.makeSignedKey(c, false)
	expired := s.makeSignedKey(c, true)

	s.store.AddKey("good.host", "sam", good)
	s.store.AddKey("expired.host", "sam", expired)

	// get all keys back. only "good" key should be returned:
	keys, _ := s.store.GetKeys("sam")
	c.Assert(keys, check.HasLen, 1)
	c.Assert(keys[0], check.DeepEquals, *good)
}

func (s *KeyStoreTestSuite) TestKnownHosts(c *check.C) {
	os.MkdirAll(s.store.KeyDir, 0777)
	pub, _, _, _, err := ssh.ParseAuthorizedKey(CAPub)
	c.Assert(err, check.IsNil)

	_, p2, _ := s.keygen.GenerateKeyPair("")
	pub2, _, _, _, _ := ssh.ParseAuthorizedKey(p2)

	err = s.store.AddKnownHostKeys("example.com", []ssh.PublicKey{pub})
	c.Assert(err, check.IsNil)
	err = s.store.AddKnownHostKeys("example.com", []ssh.PublicKey{pub2})
	c.Assert(err, check.IsNil)
	err = s.store.AddKnownHostKeys("example.org", []ssh.PublicKey{pub2})
	c.Assert(err, check.IsNil)

	keys, err := s.store.GetKnownHostKeys("")
	c.Assert(err, check.IsNil)
	c.Assert(keys, check.HasLen, 3)
	c.Assert(keys, check.DeepEquals, []ssh.PublicKey{pub, pub2, pub2})

	// check against dupes:
	before, _ := s.store.GetKnownHostKeys("")
	s.store.AddKnownHostKeys("example.org", []ssh.PublicKey{pub2})
	s.store.AddKnownHostKeys("example.org", []ssh.PublicKey{pub2})
	after, _ := s.store.GetKnownHostKeys("")
	c.Assert(len(before), check.Equals, len(after))

	// check by hostname:
	keys, _ = s.store.GetKnownHostKeys("badhost")
	c.Assert(len(keys), check.Equals, 0)
	keys, _ = s.store.GetKnownHostKeys("example.org")
	c.Assert(len(keys), check.Equals, 1)
	c.Assert(sshutils.KeysEqual(keys[0], pub2), check.Equals, true)
}

// makeSIgnedKey helper returns all 3 components of a user key (signed by CAPriv key)
func (s *KeyStoreTestSuite) makeSignedKey(c *check.C, makeExpired bool) *Key {
	var (
		err             error
		priv, pub, cert []byte
	)
	priv, pub, _ = s.keygen.GenerateKeyPair("")
	username := "vincento"
	allowedLogins := []string{username, "root"}
{'fraction_non_alphanumeric': 0.15958725706271287, 'fraction_numerical': 0.007613704668403126, 'mean_word_length': 4.449235807860262, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3072743', 'n_tokens_mistral': 3951, 'n_tokens_neox': 3812, 'n_words': 858}