Ejemplo n.º 1
0
func TestRaiseWithGenerateIdAndErase(t *testing.T) {
	// RaiseWithGenerateId api.Alerts Id : 1

	raiseAlerts, err := kva.RaiseWithGenerateId(api.Alerts{Resource: api.ResourceType_VOLUMES, Severity: api.SeverityType_NOTIFY}, mockGenerateId)
	require.NoError(t, err, "Failed in raising an alert")

	kv := kvdb.Instance()
	var alert api.Alerts

	_, err = kv.GetVal(getResourceKey(api.ResourceType_VOLUMES)+strconv.FormatInt(raiseAlerts.Id, 10), &alert)
	require.NoError(t, err, "Failed to retrieve alert from kvdb")
	require.NotNil(t, alert, "api.Alerts object null in kvdb")
	require.Equal(t, raiseAlerts.Id, alert.Id, "api.Alerts Id mismatch")
	require.Equal(t, api.ResourceType_VOLUMES, alert.Resource, "api.Alerts Resource mismatch")
	require.Equal(t, api.SeverityType_NOTIFY, alert.Severity, "api.Alerts Severity mismatch")

	// RaiseWithGenerateId api.Alerts with no Resource
	_, err = kva.RaiseWithGenerateId(api.Alerts{Severity: api.SeverityType_NOTIFY}, mockGenerateId)
	require.Error(t, err, "An error was expected")
	require.Equal(t, ErrResourceNotFound, err, "Error mismatch")

	// Erase api.Alerts Id : 1
	err = kva.Erase(api.ResourceType_VOLUMES, raiseAlerts.Id)
	require.NoError(t, err, "Failed to erase an alert")

	_, err = kv.GetVal(getResourceKey(api.ResourceType_VOLUMES)+"1", &alert)
	require.Error(t, err, "api.Alerts not erased from kvdb")

}
Ejemplo n.º 2
0
func TestProperReturn(t *testing.T) {
	t.Log("it returns nil without error")
	{
		require.NoError(t, properReturn(nil, ""))
	}

	t.Log("it returns nil without error")
	{
		require.NoError(t, properReturn(nil, "msg"))
	}

	t.Log("it returns error")
	{
		require.Error(t, properReturn(errors.New("error"), ""))
	}

	t.Log("it returns fallback message if error is exit status error and fallback message provided")
	{
		err := properReturn(errors.New("exit status 1"), "")
		require.Error(t, err)
		require.Equal(t, "exit status 1", err.Error())
	}

	t.Log("it returns fallback message if error is exit status error")
	{
		err := properReturn(errors.New("exit status 1"), "msg")
		require.Error(t, err)
		require.Equal(t, "msg", err.Error())
	}
}
Ejemplo n.º 3
0
func TestDownloadRootCAWrongCAHash(t *testing.T) {
	tc := testutils.NewTestCA(t)
	defer tc.Stop()

	// Remove the CA cert
	os.RemoveAll(tc.Paths.RootCA.Cert)

	// invalid token
	for _, invalid := range []string{
		"invalidtoken", // completely invalid
		"SWMTKN-1-3wkodtpeoipd1u1hi0ykdcdwhw16dk73ulqqtn14b3indz68rf-4myj5xihyto11dg1cn55w8p6", // mistyped
	} {
		_, err := ca.DownloadRootCA(tc.Context, tc.Paths.RootCA, invalid, tc.ConnBroker)
		require.Error(t, err)
		require.Contains(t, err.Error(), "invalid join token")
	}

	// invalid hash token
	splitToken := strings.Split(tc.ManagerToken, "-")
	splitToken[2] = "1kxftv4ofnc6mt30lmgipg6ngf9luhwqopfk1tz6bdmnkubg0e"
	replacementToken := strings.Join(splitToken, "-")

	os.RemoveAll(tc.Paths.RootCA.Cert)

	_, err := ca.DownloadRootCA(tc.Context, tc.Paths.RootCA, replacementToken, tc.ConnBroker)
	require.Error(t, err)
	require.Contains(t, err.Error(), "remote CA does not match fingerprint.")
}
Ejemplo n.º 4
0
func TestNextTopicLevelFailure(t *testing.T) {
	topics := [][]byte{
		[]byte("sport/tennis#"),
		[]byte("sport/tennis/#/ranking"),
		[]byte("sport+"),
	}

	var (
		rem []byte
		err error
	)

	_, rem, err = nextTopicLevel(topics[0])
	require.NoError(t, err)

	_, rem, err = nextTopicLevel(rem)
	require.Error(t, err)

	_, rem, err = nextTopicLevel(topics[1])
	require.NoError(t, err)

	_, rem, err = nextTopicLevel(rem)
	require.NoError(t, err)

	_, rem, err = nextTopicLevel(rem)
	require.Error(t, err)

	_, rem, err = nextTopicLevel(topics[2])
	require.Error(t, err)
}
Ejemplo n.º 5
0
func TestMemoryStore(t *testing.T) {
	s := NewMemoryStore(nil)
	_, err := s.GetMeta("nonexistent", 0)
	require.Error(t, err)
	require.IsType(t, ErrMetaNotFound{}, err)

	metaContent := []byte("content")
	metaSize := int64(7)
	err = s.SetMeta("exists", metaContent)
	require.NoError(t, err)

	meta, err := s.GetMeta("exists", metaSize)
	require.NoError(t, err)
	require.Equal(t, metaContent, meta)

	meta, err = s.GetMeta("exists", -1)
	require.NoError(t, err)
	require.Equal(t, metaContent, meta)

	err = s.RemoveAll()
	require.NoError(t, err)

	_, err = s.GetMeta("exists", 0)
	require.Error(t, err)
	require.IsType(t, ErrMetaNotFound{}, err)
}
Ejemplo n.º 6
0
func TestConfigLoadEncryptedFailures(t *testing.T) {
	var err error

	// This file should be too short to be decoded.
	oldConfigPath := ConfigPath
	ConfigPath = "./testdata/enc-short.conf"
	defer func() { ConfigPath = oldConfigPath }()
	_, err = loadConfigFile()
	require.Error(t, err)

	// This file contains invalid base64 characters.
	ConfigPath = "./testdata/enc-invalid.conf"
	_, err = loadConfigFile()
	require.Error(t, err)

	// This file contains invalid base64 characters.
	ConfigPath = "./testdata/enc-too-new.conf"
	_, err = loadConfigFile()
	require.Error(t, err)

	// This file does not exist.
	ConfigPath = "./testdata/filenotfound.conf"
	c, err := loadConfigFile()
	assert.Equal(t, errorConfigFileNotFound, err)
	assert.Nil(t, c)
}
Ejemplo n.º 7
0
func TestFailsWithoutGopath(t *testing.T) {
	pkg := "github.com/stretchr/testify"
	tester := &Test{}

	require.Error(t, tester.Get(pkg))
	require.Error(t, tester.Test(pkg))
}
func TestUnusedCompiledLibrariesRemoverNoUsedLibraries(t *testing.T) {
	temp, err := ioutil.TempDir("", "test")
	NoError(t, err)
	defer os.RemoveAll(temp)

	NoError(t, os.MkdirAll(filepath.Join(temp, "SPI"), os.FileMode(0755)))
	NoError(t, os.MkdirAll(filepath.Join(temp, "Bridge"), os.FileMode(0755)))
	NoError(t, ioutil.WriteFile(filepath.Join(temp, "dummy_file"), []byte{}, os.FileMode(0644)))

	context := make(map[string]interface{})
	context[constants.CTX_LIBRARIES_BUILD_PATH] = temp
	context[constants.CTX_IMPORTED_LIBRARIES] = []*types.Library{}

	cmd := builder.UnusedCompiledLibrariesRemover{}
	err = cmd.Run(context)
	NoError(t, err)

	_, err = os.Stat(filepath.Join(temp, "SPI"))
	require.Error(t, err)
	require.True(t, os.IsNotExist(err))
	_, err = os.Stat(filepath.Join(temp, "Bridge"))
	require.Error(t, err)
	require.True(t, os.IsNotExist(err))
	_, err = os.Stat(filepath.Join(temp, "dummy_file"))
	NoError(t, err)
}
Ejemplo n.º 9
0
// This test determines the behavior of codec with respect to advancing the
// Reader when decoding error scenarios. It seems that the codec advances
// the Reader if Decode fails, but sets its own state to expect a specific
// type for the next Decode, and thus is functionally the same as not
// advancing the Reader.
func TestCodec(t *testing.T) {
	var buf bytes.Buffer
	mh := &codec.MsgpackHandle{WriteExt: true}
	enc := codec.NewEncoder(&buf, mh)
	dec := codec.NewDecoder(&buf, mh)

	var i int = math.MaxInt32
	err := enc.Encode(i)
	require.Nil(t, err, "expected encoding to succeed")
	require.Equal(t, 5, len(buf.Bytes()), "expected buffer to contain bytes")

	var targetInt int
	err = dec.Decode(&targetInt)
	require.Nil(t, err, "expected decoding to succeed")
	require.Equal(t, math.MaxInt32, targetInt, "expected codec to successfully decode int")
	require.Equal(t, 0, len(buf.Bytes()), "expected buffer to be empty")

	var targetString string
	enc.Encode(i)
	require.Equal(t, 5, len(buf.Bytes()), "expected buffer to contain bytes")
	err = dec.Decode(&targetString)
	require.Error(t, err, "expected error while decoding")
	require.Contains(t, err.Error(), "Unrecognized descriptor byte", "expected error while decoding")
	require.Equal(t, 4, len(buf.Bytes()), "expected buffer to have bytes")
	err = dec.Decode(&targetString)
	require.Error(t, err, "expected error while decoding")
	require.Contains(t, err.Error(), "Unrecognized descriptor byte", "expected error while decoding")
	require.Equal(t, 4, len(buf.Bytes()), "expected buffer to have bytes")

	targetInt = 0
	err = dec.Decode(&targetInt)
	require.Nil(t, err, "expected decoding to succeed")
	require.Equal(t, math.MaxInt32, targetInt, "expected codec to successfully decode int")
	require.Equal(t, 0, len(buf.Bytes()), "expected buffer to be empty")
}
Ejemplo n.º 10
0
func TestMessage(t *testing.T) {

	// get data
	m, err := NewMessage(CmdRequest, "data")
	require.NoError(t, err)
	require.Equal(t, CmdRequest, m.Cmd)
	recvStr := ""
	err = m.GetData(&recvStr)
	require.NoError(t, err)

	assert.Equal(t, "data", recvStr)

	err = m.SetData("data2")
	require.NoError(t, err)
	m.GetData(&recvStr)
	assert.Equal(t, "data2", recvStr)

	recvInt := 1
	err = m.GetData(&recvInt)
	require.Error(t, err)

	m.Data = nil
	err = m.GetData(recvInt)
	assert.NoError(t, err)

	err = m.SetData(make(chan struct{}))
	require.Error(t, err)

}
Ejemplo n.º 11
0
// TestHealthCheckForOverallStatus query for signer's overall health status
func TestHealthCheckForOverallStatus(t *testing.T) {
	hs := health.NewServer()

	s := getStubbedHealthServer(hs)
	signerClient, _, cleanup := setUpSignerClient(t, s)
	defer cleanup()

	// both of the service are NOT SERVING, expect the health check for overall status to be failed.
	hs.SetServingStatus(notary.HealthCheckKeyManagement, healthpb.HealthCheckResponse_NOT_SERVING)
	hs.SetServingStatus(notary.HealthCheckSigner, healthpb.HealthCheckResponse_NOT_SERVING)
	err := signerClient.CheckHealth(1*time.Second, notary.HealthCheckOverall)
	require.Error(t, err)
	require.Contains(t, err.Error(), "NOT_SERVING, want SERVING")

	// change the status of KeyManagement to SERVING and keep the status of Signer
	// still be NOT SERVING, expect the health check for overall status to be failed.
	hs.SetServingStatus(notary.HealthCheckKeyManagement, healthpb.HealthCheckResponse_SERVING)
	err = signerClient.CheckHealth(1*time.Second, notary.HealthCheckOverall)
	require.Error(t, err)
	require.Contains(t, err.Error(), "NOT_SERVING, want SERVING")

	// change the status of Signer to SERVING, expect the health check for overall status to success.
	hs.SetServingStatus(notary.HealthCheckSigner, healthpb.HealthCheckResponse_SERVING)
	err = signerClient.CheckHealth(1*time.Second, notary.HealthCheckOverall)
	require.NoError(t, err)

}
Ejemplo n.º 12
0
func TestConfigLoadEncryptedFailures(t *testing.T) {
	var err error

	// This file should be too short to be decoded.
	oldConfigPath := ConfigPath
	ConfigPath = "./testdata/enc-short.conf"
	defer func() { ConfigPath = oldConfigPath }()
	_, err = loadConfigFile()
	require.Error(t, err)

	// This file contains invalid base64 characters.
	ConfigPath = "./testdata/enc-invalid.conf"
	_, err = loadConfigFile()
	require.Error(t, err)

	// This file contains invalid base64 characters.
	ConfigPath = "./testdata/enc-too-new.conf"
	_, err = loadConfigFile()
	require.Error(t, err)

	// This file contains invalid base64 characters.
	ConfigPath = "./testdata/filenotfound.conf"
	c, err := loadConfigFile()
	require.NoError(t, err)
	require.Len(t, c.GetSectionList(), 0, "Expected 0-length section")
}
Ejemplo n.º 13
0
func TestMergeErrors(t *testing.T) {
	// Cannot Merge in an invalid ring
	ring1 := New(start, end, peer1name)
	ring2 := New(start, end, peer2name)
	ring2.Entries = []*entry{{Token: middle, Peer: peer2name}, {Token: start, Peer: peer2name}}
	require.True(t, ring1.Merge(*ring2) == ErrNotSorted, "Expected ErrNotSorted")

	// Should Merge two rings for different ranges
	ring2 = New(start, middle, peer2name)
	ring2.Entries = []*entry{}
	require.True(t, ring1.Merge(*ring2) == ErrDifferentRange, "Expected ErrDifferentRange")

	// Cannot Merge newer version of entry I own
	ring2 = New(start, end, peer2name)
	ring1.Entries = []*entry{{Token: start, Peer: peer1name}}
	ring2.Entries = []*entry{{Token: start, Peer: peer1name, Version: 1}}
	fmt.Println(ring1.Merge(*ring2))
	require.Error(t, ring1.Merge(*ring2), "Expected error")

	// Cannot Merge two entries with same version but different hosts
	ring1.Entries = []*entry{{Token: start, Peer: peer1name}}
	ring2.Entries = []*entry{{Token: start, Peer: peer2name}}
	require.Error(t, ring1.Merge(*ring2), "Expected error")

	// Cannot Merge an entry into a range I own
	ring1.Entries = []*entry{{Token: start, Peer: peer1name}}
	ring2.Entries = []*entry{{Token: middle, Peer: peer2name}}
	require.Error(t, ring1.Merge(*ring2), "Expected error")
}
Ejemplo n.º 14
0
// If the snapshot is loaded first (-ish, because really root has to be loaded first)
// it will be used to validate the checksums of all other metadata that gets loaded.
// If the checksum doesn't match, or if there is no checksum, then the other metadata
// cannot be loaded.
func TestSnapshotLoadedFirstChecksumsOthers(t *testing.T) {
	gun := "docker.com/notary"
	meta := setupSnapshotChecksumming(t, gun)
	// --- load root then snapshot
	builder := tuf.NewRepoBuilder(gun, nil, trustpinning.TrustPinConfig{})
	require.NoError(t, builder.Load(data.CanonicalRootRole, meta[data.CanonicalRootRole], 1, false))
	require.NoError(t, builder.Load(data.CanonicalSnapshotRole, meta[data.CanonicalSnapshotRole], 1, false))

	// loading timestamp is fine, even though the timestamp metadata has the wrong checksum because
	// we don't check timestamp checksums
	require.NoError(t, builder.Load(data.CanonicalTimestampRole, meta[data.CanonicalTimestampRole], 1, false))

	// loading the other roles' metadata with a space will fail because of a checksum failure (builder
	// checks right away if the snapshot is loaded) - in the case of targets/other/other, which should
	// not be in snapshot at all, loading should fail even without a space because there is no checksum
	// for it
	for _, roleNameToLoad := range []string{data.CanonicalTargetsRole, "targets/other"} {
		err := builder.Load(roleNameToLoad, append(meta[roleNameToLoad], ' '), 0, false)
		require.Error(t, err)
		checksumErr, ok := err.(data.ErrMismatchedChecksum)
		require.True(t, ok)
		require.Contains(t, checksumErr.Error(), fmt.Sprintf("checksum for %s did not match", roleNameToLoad))
		require.False(t, builder.IsLoaded(roleNameToLoad))

		// now load it for real (since we need targets loaded before trying to load "targets/other")
		require.NoError(t, builder.Load(roleNameToLoad, meta[roleNameToLoad], 1, false))
	}
	// loading the non-existent role wil fail
	err := builder.Load("targets/other/other", meta["targets/other/other"], 1, false)
	require.Error(t, err)
	require.IsType(t, data.ErrMissingMeta{}, err)
	require.False(t, builder.IsLoaded("targets/other/other"))
}
func TestUnusedCompiledLibrariesRemoverNoUsedLibraries(t *testing.T) {
	temp, err := ioutil.TempDir("", "test")
	NoError(t, err)
	defer os.RemoveAll(temp)

	NoError(t, os.MkdirAll(filepath.Join(temp, "SPI"), os.FileMode(0755)))
	NoError(t, os.MkdirAll(filepath.Join(temp, "Bridge"), os.FileMode(0755)))
	NoError(t, ioutil.WriteFile(filepath.Join(temp, "dummy_file"), []byte{}, os.FileMode(0644)))

	ctx := &types.Context{}
	ctx.LibrariesBuildPath = temp
	ctx.ImportedLibraries = []*types.Library{}

	cmd := builder.UnusedCompiledLibrariesRemover{}
	err = cmd.Run(ctx)
	NoError(t, err)

	_, err = os.Stat(filepath.Join(temp, "SPI"))
	require.Error(t, err)
	require.True(t, os.IsNotExist(err))
	_, err = os.Stat(filepath.Join(temp, "Bridge"))
	require.Error(t, err)
	require.True(t, os.IsNotExist(err))
	_, err = os.Stat(filepath.Join(temp, "dummy_file"))
	NoError(t, err)
}
Ejemplo n.º 16
0
func TestPassword(t *testing.T) {
	defer func() {
		configKey = nil // reset password
	}()
	var err error
	// Empty password should give error
	err = setPassword("  \t  ")
	require.Error(t, err)

	// Test invalid utf8 sequence
	err = setPassword(string([]byte{0xff, 0xfe, 0xfd}) + "abc")
	require.Error(t, err)

	// Simple check of wrong passwords
	hashedKeyCompare(t, "mis", "match", false)

	// Check that passwords match with trimmed whitespace
	hashedKeyCompare(t, "   abcdef   \t", "abcdef", true)

	// Check that passwords match after unicode normalization
	hashedKeyCompare(t, "ff\u0041\u030A", "ffÅ", true)

	// Check that passwords preserves case
	hashedKeyCompare(t, "abcdef", "ABCDEF", false)

}
Ejemplo n.º 17
0
func TestPassphraseRetrieverDelegationRoleCaching(t *testing.T) {
	defer cleanupAndSetEnvVars()()
	// Only set up one passphrase environment var first for delegations
	require.NoError(t, os.Setenv("NOTARY_DELEGATION_PASSPHRASE", "delegation_passphrase"))

	// Check that any delegation role is cached
	retriever := getPassphraseRetriever()

	passphrase, giveup, err := retriever("key", "targets/releases", false, 0)
	require.NoError(t, err)
	require.False(t, giveup)
	require.Equal(t, passphrase, "delegation_passphrase")
	passphrase, giveup, err = retriever("key", "targets/delegation", false, 0)
	require.NoError(t, err)
	require.False(t, giveup)
	require.Equal(t, passphrase, "delegation_passphrase")
	passphrase, giveup, err = retriever("key", "targets/a/b/c/d", false, 0)
	require.NoError(t, err)
	require.False(t, giveup)
	require.Equal(t, passphrase, "delegation_passphrase")

	// Also check arbitrary usernames that are non-BaseRoles or imported so that this can be shared across keys
	passphrase, giveup, err = retriever("key", "user", false, 0)
	require.NoError(t, err)
	require.False(t, giveup)
	require.Equal(t, passphrase, "delegation_passphrase")

	// Make sure base roles fail
	_, _, err = retriever("key", data.CanonicalRootRole, false, 0)
	require.Error(t, err)
	_, _, err = retriever("key", data.CanonicalTargetsRole, false, 0)
	require.Error(t, err)
	_, _, err = retriever("key", data.CanonicalSnapshotRole, false, 0)
	require.Error(t, err)
}
Ejemplo n.º 18
0
func TestMessageHeaderFields(t *testing.T) {
	header := &header{}

	header.SetRemainingLength(33)

	require.Equal(t, 33, header.RemainingLength())

	err := header.SetRemainingLength(268435456)

	require.Error(t, err)

	err = header.SetRemainingLength(-1)

	require.Error(t, err)

	err = header.SetType(RESERVED)

	require.Error(t, err)

	err = header.SetType(PUBREL)

	require.NoError(t, err)
	require.Equal(t, PUBREL, header.Type())
	require.Equal(t, "PUBREL", header.Name())
	require.Equal(t, 2, int(header.Flags()))
}
Ejemplo n.º 19
0
func TestValidateRootCanContainOnlyx509KeysWithRightGun(t *testing.T) {
	gun := "docker.com/notary"
	repo, cs, err := testutils.EmptyRepo("wrong/gun")
	require.NoError(t, err)
	serverCrypto := testutils.CopyKeys(t, cs, data.CanonicalTimestampRole)

	// if the root has the wrong gun, the server will fail to validate
	r, tg, sn, ts, err := testutils.Sign(repo)
	require.NoError(t, err)
	root, targets, snapshot, timestamp, err := getUpdates(r, tg, sn, ts)
	require.NoError(t, err)

	_, err = validateUpdate(serverCrypto, gun,
		[]storage.MetaUpdate{root, targets, snapshot, timestamp},
		storage.NewMemStorage())
	require.Error(t, err)
	require.IsType(t, validation.ErrBadRoot{}, err)

	// create regular non-x509 keys - change the root keys to one that is not
	// an x509 key - it should also fail to validate
	newRootKey, err := cs.Create(data.CanonicalRootRole, gun, data.ECDSAKey)
	require.NoError(t, err)
	require.NoError(t, repo.ReplaceBaseKeys(data.CanonicalRootRole, newRootKey))

	r, tg, sn, ts, err = testutils.Sign(repo)
	require.NoError(t, err)
	root, targets, snapshot, timestamp, err = getUpdates(r, tg, sn, ts)
	require.NoError(t, err)

	_, err = validateUpdate(serverCrypto, gun,
		[]storage.MetaUpdate{root, targets, snapshot, timestamp},
		storage.NewMemStorage())
	require.Error(t, err)
	require.IsType(t, validation.ErrBadRoot{}, err)
}
Ejemplo n.º 20
0
func TestDBHealthCheck(t *testing.T) {
	tempBaseDir, err := ioutil.TempDir("/tmp", "notary-test-")
	defer os.RemoveAll(tempBaseDir)

	// Create a new KeyDB store
	dbStore, err := NewKeyDBStore(retriever, "ignoredalias",
		"sqlite3", filepath.Join(tempBaseDir, "test_db"))
	require.NoError(t, err)

	// No key table, health check fails
	err = dbStore.HealthCheck()
	require.Error(t, err, "Cannot access table:")

	// Ensure that the private_key table exists
	dbStore.db.CreateTable(&GormPrivateKey{})

	// Heath check success because the table exists
	err = dbStore.HealthCheck()
	require.NoError(t, err)

	// Close the connection
	err = dbStore.db.Close()
	require.NoError(t, err)

	// Heath check fail because the connection is closed
	err = dbStore.HealthCheck()
	require.Error(t, err, "Cannot access table:")
}
Ejemplo n.º 21
0
func TestAddInvalidDelegationCert(t *testing.T) {
	// Setup certificate
	tempFile, err := ioutil.TempFile("", "pemfile")
	require.NoError(t, err)
	cert, _, err := generateExpiredTestCert()
	require.NoError(t, err)
	_, err = tempFile.Write(utils.CertToPEM(cert))
	require.NoError(t, err)
	tempFile.Close()
	defer os.Remove(tempFile.Name())

	// Setup commander
	tmpDir, err := ioutil.TempDir("", "notary-cmd-test-")
	require.NoError(t, err)
	defer os.RemoveAll(tmpDir)
	commander := setup(tmpDir)

	// Should error due to expired cert
	err = commander.delegationAdd(commander.GetCommand(), []string{"gun", "targets/delegation", tempFile.Name(), "--paths", "path"})
	require.Error(t, err)

	// Should error due to bad path
	err = commander.delegationAdd(commander.GetCommand(), []string{"gun", "targets/delegation", "nonexistent-pathing", "--paths", "path"})
	require.Error(t, err)
	require.Contains(t, err.Error(), "file for public key does not exist")
}
Ejemplo n.º 22
0
func TestBuilderOnlyAcceptsDelegationsAfterParent(t *testing.T) {
	meta, gun := getSampleMeta(t)
	builder := tuf.NewRepoBuilder(gun, nil, trustpinning.TrustPinConfig{})

	// load the root
	require.NoError(t, builder.Load(data.CanonicalRootRole, meta[data.CanonicalRootRole], 1, false))

	// delegations can't be loaded without target
	for _, delgName := range []string{"targets/a", "targets/a/b"} {
		err := builder.Load(delgName, meta[delgName], 1, false)
		require.Error(t, err)
		require.IsType(t, tuf.ErrInvalidBuilderInput{}, err)
		require.Contains(t, err.Error(), "targets must be loaded first")
		require.False(t, builder.IsLoaded(delgName))
		require.Equal(t, 1, builder.GetLoadedVersion(delgName))
	}

	// load the targets
	require.NoError(t, builder.Load(data.CanonicalTargetsRole, meta[data.CanonicalTargetsRole], 1, false))

	// targets/a/b can't be loaded because targets/a isn't loaded
	err := builder.Load("targets/a/b", meta["targets/a/b"], 1, false)
	require.Error(t, err)
	require.IsType(t, data.ErrInvalidRole{}, err)

	// targets/a can be loaded now though because targets is loaded
	require.NoError(t, builder.Load("targets/a", meta["targets/a"], 1, false))

	// and now targets/a/b can be loaded because targets/a is loaded
	require.NoError(t, builder.Load("targets/a/b", meta["targets/a/b"], 1, false))
}
Ejemplo n.º 23
0
func Test_GlobalFlagPRTrigger(t *testing.T) {
	configPth := "global_flag_test_bitrise.yml"
	secretsPth := "global_flag_test_secrets.yml"

	prModeEnv := os.Getenv(configs.PRModeEnvKey)
	prIDEnv := os.Getenv(configs.PullRequestIDEnvKey)

	// cleanup Envs after these tests
	defer func() {
		require.NoError(t, os.Setenv(configs.PRModeEnvKey, prModeEnv))
		require.NoError(t, os.Setenv(configs.PullRequestIDEnvKey, prIDEnv))
	}()

	require.NoError(t, os.Setenv(configs.PRModeEnvKey, "false"))
	require.NoError(t, os.Setenv(configs.PullRequestIDEnvKey, ""))

	t.Log("global flag sets pr mode")
	{
		cmd := cmdex.NewCommand(binPath(), "--pr", "trigger", "deprecated_pr", "--config", configPth, "--inventory", secretsPth)
		out, err := cmd.RunAndReturnTrimmedCombinedOutput()
		require.Error(t, err, out)
	}

	t.Log("global flag sets pr mode")
	{
		cmd := cmdex.NewCommand(binPath(), "--pr=true", "trigger", "deprecated_pr", "--config", configPth, "--inventory", secretsPth)
		out, err := cmd.RunAndReturnTrimmedCombinedOutput()
		require.Error(t, err, out)
	}
}
Ejemplo n.º 24
0
// UpdateMany does not insert any rows (or at least rolls them back) if there
// are any conflicts.
func testUpdateManyConflictRollback(t *testing.T, s MetaStore) []StoredTUFMeta {
	gun := "testGUN"
	successBatch := make([]StoredTUFMeta, 4)
	updates := make([]MetaUpdate, 4)
	for i, role := range data.BaseRoles {
		successBatch[i] = SampleCustomTUFObj(gun, role, 1, nil)
		updates[i] = MakeUpdate(successBatch[i])
	}

	require.NoError(t, s.UpdateMany(gun, updates))

	before, err := s.GetChanges("0", 1000, "")
	if _, ok := s.(RethinkDB); !ok {
		require.NoError(t, err)
	}

	// conflicts with what's in DB
	badBatch := make([]StoredTUFMeta, 4)
	for i, role := range data.BaseRoles {
		version := 2
		if role == data.CanonicalTargetsRole {
			version = 1
		}
		tufdata := []byte(fmt.Sprintf("%s_%s_%d_bad", gun, role, version))
		badBatch[i] = SampleCustomTUFObj(gun, role, version, tufdata)
		updates[i] = MakeUpdate(badBatch[i])
	}

	// check no changes were written when there was a conflict+rollback
	after, err := s.GetChanges("0", 1000, "")
	if _, ok := s.(RethinkDB); !ok {
		require.NoError(t, err)
	}
	require.Equal(t, len(before), len(after))

	err = s.UpdateMany(gun, updates)
	require.Error(t, err)
	require.IsType(t, ErrOldVersion{}, err)

	// self-conflicting, in that it's a duplicate, but otherwise no DB conflicts
	duplicate := SampleCustomTUFObj(gun, data.CanonicalTimestampRole, 3, []byte("duplicate"))
	duplicateUpdate := MakeUpdate(duplicate)
	err = s.UpdateMany(gun, []MetaUpdate{duplicateUpdate, duplicateUpdate})
	require.Error(t, err)
	require.IsType(t, ErrOldVersion{}, err)

	assertExpectedTUFMetaInStore(t, s, successBatch, true)

	for _, tufObj := range append(badBatch, duplicate) {
		checksumBytes := sha256.Sum256(tufObj.Data)
		checksum := hex.EncodeToString(checksumBytes[:])

		_, _, err = s.GetChecksum(tufObj.Gun, tufObj.Role, checksum)
		require.Error(t, err)
		require.IsType(t, ErrNotFound{}, err)
	}

	return successBatch
}
Ejemplo n.º 25
0
func TestValidateStepInputOutputModel(t *testing.T) {
	// Filled env
	env := envmanModels.EnvironmentItemModel{
		"test_key": "test_value",
		envmanModels.OptionsKey: envmanModels.EnvironmentItemOptionsModel{
			Title:             pointers.NewStringPtr("test_title"),
			Description:       pointers.NewStringPtr("test_description"),
			Summary:           pointers.NewStringPtr("test_summary"),
			ValueOptions:      []string{"test_key2", "test_value2"},
			IsRequired:        pointers.NewBoolPtr(true),
			IsExpand:          pointers.NewBoolPtr(false),
			IsDontChangeValue: pointers.NewBoolPtr(true),
		},
	}

	step := StepModel{
		Inputs: []envmanModels.EnvironmentItemModel{env},
	}

	require.NoError(t, step.ValidateInputAndOutputEnvs(true))

	// Empty key
	env = envmanModels.EnvironmentItemModel{
		"": "test_value",
		envmanModels.OptionsKey: envmanModels.EnvironmentItemOptionsModel{
			Title:             pointers.NewStringPtr("test_title"),
			Description:       pointers.NewStringPtr("test_description"),
			Summary:           pointers.NewStringPtr("test_summary"),
			ValueOptions:      []string{"test_key2", "test_value2"},
			IsRequired:        pointers.NewBoolPtr(true),
			IsExpand:          pointers.NewBoolPtr(false),
			IsDontChangeValue: pointers.NewBoolPtr(true),
		},
	}

	step = StepModel{
		Inputs: []envmanModels.EnvironmentItemModel{env},
	}

	require.Error(t, step.ValidateInputAndOutputEnvs(true))

	// Title is empty
	env = envmanModels.EnvironmentItemModel{
		"test_key": "test_value",
		envmanModels.OptionsKey: envmanModels.EnvironmentItemOptionsModel{
			Description:       pointers.NewStringPtr("test_description"),
			ValueOptions:      []string{"test_key2", "test_value2"},
			IsRequired:        pointers.NewBoolPtr(true),
			IsExpand:          pointers.NewBoolPtr(false),
			IsDontChangeValue: pointers.NewBoolPtr(true),
		},
	}

	step = StepModel{
		Inputs: []envmanModels.EnvironmentItemModel{env},
	}

	require.Error(t, step.ValidateInputAndOutputEnvs(true))
}
Ejemplo n.º 26
0
// No matter what order timestamp and snapshot is loaded, if the snapshot's checksum doesn't match
// what's in the timestamp, the builder will error and refuse to load the latest piece of metadata
// whether that is snapshot (because it was loaded after timestamp) or timestamp (because builder
// retroactive checks the loaded snapshot's checksum).  Timestamp ONLY checks the snapshot checksum.
func TestTimestampPreAndPostChecksumming(t *testing.T) {
	gun := "docker.com/notary"
	repo, _, err := testutils.EmptyRepo(gun, "targets/other", "targets/other/other")
	require.NoError(t, err)

	// add invalid checkums for all the other roles to timestamp too, and show that
	// cached items aren't checksummed against this
	fakeChecksum, err := data.NewFileMeta(bytes.NewBuffer([]byte("fake")), notary.SHA256, notary.SHA512)
	require.NoError(t, err)
	for _, roleName := range append(data.BaseRoles, "targets/other") {
		// add a wrong checksum for every role, including timestamp itself
		repo.Timestamp.Signed.Meta[roleName] = fakeChecksum
	}
	// this will overwrite the snapshot checksum with the right one
	meta, err := testutils.SignAndSerialize(repo)
	require.NoError(t, err)
	// ensure that the fake meta for other roles weren't destroyed by signing the timestamp
	require.Len(t, repo.Timestamp.Signed.Meta, 5)

	snapJSON := append(meta[data.CanonicalSnapshotRole], ' ')

	// --- load timestamp first
	builder := tuf.NewRepoBuilder(gun, nil, trustpinning.TrustPinConfig{})
	require.NoError(t, builder.Load(data.CanonicalRootRole, meta[data.CanonicalRootRole], 1, false))
	// timestamp doesn't fail, even though its checksum for root is wrong according to timestamp
	require.NoError(t, builder.Load(data.CanonicalTimestampRole, meta[data.CanonicalTimestampRole], 1, false))
	// loading the snapshot in fails, because of the checksum the timestamp has
	err = builder.Load(data.CanonicalSnapshotRole, snapJSON, 1, false)
	require.Error(t, err)
	require.IsType(t, data.ErrMismatchedChecksum{}, err)
	require.True(t, builder.IsLoaded(data.CanonicalTimestampRole))
	require.False(t, builder.IsLoaded(data.CanonicalSnapshotRole))
	// all the other metadata can be loaded in, even though the checksums are wrong according to timestamp
	for _, roleName := range []string{data.CanonicalTargetsRole, "targets/other"} {
		require.NoError(t, builder.Load(roleName, meta[roleName], 1, false))
	}

	// --- load snapshot first
	builder = tuf.NewRepoBuilder(gun, nil, trustpinning.TrustPinConfig{})
	for _, roleName := range append(data.BaseRoles, "targets/other") {
		switch roleName {
		case data.CanonicalTimestampRole:
			continue
		case data.CanonicalSnapshotRole:
			require.NoError(t, builder.Load(roleName, snapJSON, 1, false))
		default:
			require.NoError(t, builder.Load(roleName, meta[roleName], 1, false))
		}
	}
	// timestamp fails because the snapshot checksum is wrong
	err = builder.Load(data.CanonicalTimestampRole, meta[data.CanonicalTimestampRole], 1, false)
	require.Error(t, err)
	checksumErr, ok := err.(data.ErrMismatchedChecksum)
	require.True(t, ok)
	require.Contains(t, checksumErr.Error(), "checksum for snapshot did not match")
	require.False(t, builder.IsLoaded(data.CanonicalTimestampRole))
	require.True(t, builder.IsLoaded(data.CanonicalSnapshotRole))
}
Ejemplo n.º 27
0
func TestCompareMultiHashes(t *testing.T) {
	var err error
	hashes1 := make(Hashes)
	hashes2 := make(Hashes)

	// Expected to fail since there are no checksums at all
	err = CompareMultiHashes(hashes1, hashes2)
	require.Error(t, err)

	// Expected to pass even though the checksum of sha384 isn't a default "supported" hash algorithm valid,
	// because we haven't provided a supported hash algorithm yet (ex: sha256) for the Hashes map to be considered valid
	hashes1["sha384"], err = hex.DecodeString("64becc3c23843942b1040ffd4743d1368d988ddf046d17d448a6e199c02c3044b425a680112b399d4dbe9b35b7ccc989")
	require.NoError(t, err)
	hashes2["sha384"], err = hex.DecodeString("64becc3c23843942b1040ffd4743d1368d988ddf046d17d448a6e199c02c3044b425a680112b399d4dbe9b35b7ccc989")
	require.NoError(t, err)
	err = CompareMultiHashes(hashes1, hashes2)
	require.Error(t, err)

	// Now both have a matching sha256, so this will pass
	hashes1[notary.SHA256], err = hex.DecodeString("766af0ef090a4f2307e49160fa242db6fb95f071ad81a198eeb7d770e61cd6d8")
	require.NoError(t, err)
	hashes2[notary.SHA256], err = hex.DecodeString("766af0ef090a4f2307e49160fa242db6fb95f071ad81a198eeb7d770e61cd6d8")
	require.NoError(t, err)
	err = CompareMultiHashes(hashes1, hashes2)
	require.NoError(t, err)

	// Because the sha384 algorithm isn't a "default hash algorithm", it's still found in the intersection of keys
	// so this check will fail
	hashes2["sha384"], err = hex.DecodeString(strings.Repeat("a", 96))
	require.NoError(t, err)
	err = CompareMultiHashes(hashes1, hashes2)
	require.Error(t, err)
	delete(hashes2, "sha384")

	// only add a sha512 to hashes1, but comparison will still succeed because there's no mismatch and we have the sha256 match
	hashes1[notary.SHA512], err = hex.DecodeString("795d9e95db099464b6730844f28effddb010b0d5abae5d5892a6ee04deacb09c9e622f89e816458b5a1a81761278d7d3a6a7c269d9707eff8858b16c51de0315")
	require.NoError(t, err)
	err = CompareMultiHashes(hashes1, hashes2)
	require.NoError(t, err)

	// remove sha256 from hashes1, comparison will fail now because there are no matches
	delete(hashes1, notary.SHA256)
	err = CompareMultiHashes(hashes1, hashes2)
	require.Error(t, err)

	// add sha512 to hashes2, comparison will now pass because both have matching sha512s
	hashes2[notary.SHA512], err = hex.DecodeString("795d9e95db099464b6730844f28effddb010b0d5abae5d5892a6ee04deacb09c9e622f89e816458b5a1a81761278d7d3a6a7c269d9707eff8858b16c51de0315")
	require.NoError(t, err)
	err = CompareMultiHashes(hashes1, hashes2)
	require.NoError(t, err)

	// change the sha512 for hashes2, comparison will now fail
	hashes2[notary.SHA512], err = hex.DecodeString(strings.Repeat("a", notary.SHA512HexSize))
	require.NoError(t, err)
	err = CompareMultiHashes(hashes1, hashes2)
	require.Error(t, err)
}
Ejemplo n.º 28
0
func TestMockFailureAuthenticator(t *testing.T) {
	require.Error(t, mockFailureAuthenticator.Authenticate("", ""))

	require.Error(t, providers["mockFailure"].Authenticate("", ""))

	mgr, err := NewManager("mockFailure")
	require.NoError(t, err)
	require.Error(t, mgr.Authenticate("", ""))
}
Ejemplo n.º 29
0
func TestSelect(t *testing.T) {
	// No port specification
	_, err := runOpts(&selectOpts{}, []string{
		"foo-svc", "bar-rule", "--image", "whatever",
	})
	require.Error(t, err)

	// No such service
	_, err = runOpts(&selectOpts{}, []string{
		"doop-svc", "bar-rule", "--image", "whatever", "--port-fixed", "80",
	})
	require.Error(t, err)

	// For the ff we need a service to attach rules to
	st, err := runOpts(&addOpts{}, []string{
		"foo-svc",
	})
	require.NoError(t, err)

	// Don't select anything
	err = runOptsWithStore(&selectOpts{}, st, []string{
		"foo-svc", "empty-rule",
	})
	require.Error(t, err)

	err = runOptsWithStore(&selectOpts{}, st, []string{
		"foo-svc", "no-port-rule", "--image", "foo/bar",
	})
	require.Error(t, err)

	opts := &selectOpts{}
	bout, berr := opts.tapOutput()
	err = runOptsWithStore(opts, st, []string{
		"foo-svc", "ok-rule", "--image", "foo/bar", "--port-fixed", "80",
	})
	require.NoError(t, err)
	require.Equal(t, "ok-rule\n", bout.String())
	require.Equal(t, "", berr.String())

	svc, err := st.GetService("foo-svc", store.QueryServiceOptions{WithContainerRules: true})
	require.NoError(t, err)
	require.Len(t, svc.ContainerRules, 1)
	rule := svc.ContainerRules[0]
	require.Equal(t, store.ContainerRuleInfo{
		Name: "ok-rule",
		ContainerRule: data.ContainerRule{
			AddressSpec: data.AddressSpec{
				Type: data.FIXED,
				Port: 80,
			},
			Selector: map[string]string{
				"image": "foo/bar",
			},
		},
	}, rule)
}
Ejemplo n.º 30
0
func Test_GlobalFlagPRTriggerCheck(t *testing.T) {
	configPth := "global_flag_test_bitrise.yml"
	secretsPth := "global_flag_test_secrets.yml"

	prModeEnv := os.Getenv(configs.PRModeEnvKey)
	prIDEnv := os.Getenv(configs.PullRequestIDEnvKey)

	// cleanup Envs after these tests
	defer func() {
		require.NoError(t, os.Setenv(configs.PRModeEnvKey, prModeEnv))
		require.NoError(t, os.Setenv(configs.PullRequestIDEnvKey, prIDEnv))
	}()

	t.Log("global flag sets pr mode")
	{
		require.NoError(t, os.Setenv(configs.PRModeEnvKey, "false"))
		require.NoError(t, os.Setenv(configs.PullRequestIDEnvKey, ""))

		cmd := cmdex.NewCommand(binPath(), "--pr", "trigger-check", "deprecated_pr", "--config", configPth, "--inventory", secretsPth)
		out, err := cmd.RunAndReturnTrimmedCombinedOutput()
		require.Error(t, err, out)
	}

	t.Log("global flag sets pr mode")
	{

		require.NoError(t, os.Setenv("PR", "false"))
		require.NoError(t, os.Setenv("PULL_REQUEST_ID", ""))

		cmd := cmdex.NewCommand(binPath(), "--pr=true", "trigger-check", "deprecated_pr", "--config", configPth, "--inventory", secretsPth)
		out, err := cmd.RunAndReturnTrimmedCombinedOutput()
		require.Error(t, err, out)
	}

	t.Log("global flag sets NOT pr mode")
	{
		require.NoError(t, os.Setenv("PR", "true"))
		require.NoError(t, os.Setenv("PULL_REQUEST_ID", "ID"))

		cmd := cmdex.NewCommand(binPath(), "--pr=true", "trigger-check", "master", "--config", configPth, "--format", "json")
		out, err := cmd.RunAndReturnTrimmedCombinedOutput()
		require.NoError(t, err, out)
		require.Equal(t, `{"pattern":"master","workflow":"deprecated_pr"}`, out)
	}

	t.Log("global flag sets NOT pr mode")
	{
		require.NoError(t, os.Setenv("PR", "true"))
		require.NoError(t, os.Setenv("PULL_REQUEST_ID", "ID"))

		cmd := cmdex.NewCommand(binPath(), "--pr=false", "trigger-check", "master", "--config", configPth, "--format", "json")
		out, err := cmd.RunAndReturnTrimmedCombinedOutput()
		require.NoError(t, err, out)
		require.Equal(t, `{"pattern":"master","workflow":"deprecated_code_push"}`, out)
	}
}