Пример #1
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)

}
Пример #2
0
// If there is one key, asking to remove it will ask for confirmation.  Passing
// anything other than 'yes'/'y'/'' response will abort the deletion and
// not delete the key.
func TestRemoveOneKeyAbort(t *testing.T) {
	setUp(t)
	nos := []string{"no", "NO", "AAAARGH", "   N    "}
	store := trustmanager.NewKeyMemoryStore(ret)

	key, err := trustmanager.GenerateED25519Key(rand.Reader)
	require.NoError(t, err)
	err = store.AddKey(trustmanager.KeyInfo{Role: data.CanonicalRootRole, Gun: ""}, key)
	require.NoError(t, err)

	stores := []trustmanager.KeyStore{store}

	for _, noAnswer := range nos {
		var out bytes.Buffer
		in := bytes.NewBuffer([]byte(noAnswer + "\n"))

		err := removeKeyInteractively(stores, key.ID(), in, &out)
		require.NoError(t, err)
		text, err := ioutil.ReadAll(&out)
		require.NoError(t, err)

		output := string(text)
		require.Contains(t, output, "Are you sure")
		require.Contains(t, output, "Aborting action")
		require.Len(t, store.ListKeys(), 1)
	}
}
func TestLoadSketchFromFolder(t *testing.T) {
	ctx := &types.Context{
		SketchLocation: "sketch_with_subfolders",
	}

	commands := []types.Command{
		&builder.SketchLoader{},
	}

	for _, command := range commands {
		err := command.Run(ctx)
		NoError(t, err)
	}

	sketch := ctx.Sketch
	require.NotNil(t, sketch)

	require.Contains(t, sketch.MainFile.Name, "sketch_with_subfolders.ino")

	require.Equal(t, 0, len(sketch.OtherSketchFiles))

	require.Equal(t, 2, len(sketch.AdditionalFiles))
	require.Contains(t, sketch.AdditionalFiles[0].Name, "other.cpp")
	require.Contains(t, sketch.AdditionalFiles[1].Name, "other.h")
}
Пример #4
0
// The bare notary command and bare subcommands all print out usage
func TestBareCommandPrintsUsageAndNoError(t *testing.T) {
	tempdir, err := ioutil.TempDir("", "empty-dir")
	require.NoError(t, err)
	defer os.RemoveAll(tempdir)

	// just the notary command
	b := new(bytes.Buffer)
	cmd := NewNotaryCommand()
	cmd.SetOutput(b)

	cmd.SetArgs([]string{"-c", filepath.Join(tempdir, "idonotexist.json")})
	require.NoError(t, cmd.Execute(), "Expected no error from a help request")
	// usage is printed
	require.Contains(t, b.String(), "Usage:", "expected usage when running `notary`")

	// notary key and notary delegation
	for _, bareCommand := range []string{"key", "delegation"} {
		b := new(bytes.Buffer)
		cmd := NewNotaryCommand()
		cmd.SetOutput(b)

		cmd.SetArgs([]string{"-c", filepath.Join(tempdir, "idonotexist.json"), "-d", tempdir, bareCommand})
		require.NoError(t, cmd.Execute(), "Expected no error from a help request")
		// usage is printed
		require.Contains(t, b.String(), "Usage:", "expected usage when running `notary %s`", bareCommand)
	}
}
Пример #5
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")
}
Пример #6
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.")
}
Пример #7
0
func TestGetDelegationRolesInvalidPaths(t *testing.T) {
	ed25519 := signed.NewEd25519()
	repo := initRepo(t, ed25519)

	testKey1, err := ed25519.Create("targets/test", testGUN, data.ED25519Key)
	require.NoError(t, err)

	err = repo.UpdateDelegationKeys("targets/test", []data.PublicKey{testKey1}, []string{}, 1)
	require.NoError(t, err)
	err = repo.UpdateDelegationPaths("targets/test", []string{"path", "anotherpath"}, []string{}, false)
	require.NoError(t, err)

	testKey2, err := ed25519.Create("targets/test/b", testGUN, data.ED25519Key)
	require.NoError(t, err)
	// Now we add a delegation with a path that is not prefixed by its parent delegation, the invalid path can't be added so there is an error
	err = repo.UpdateDelegationKeys("targets/test/b", []data.PublicKey{testKey2}, []string{}, 1)
	require.NoError(t, err)
	err = repo.UpdateDelegationPaths("targets/test/b", []string{"invalidpath"}, []string{}, false)
	require.Error(t, err)
	require.IsType(t, data.ErrInvalidRole{}, err)

	delgRole, err := repo.GetDelegationRole("targets/test")
	require.NoError(t, err)
	require.Contains(t, delgRole.Paths, "path")
	require.Contains(t, delgRole.Paths, "anotherpath")
}
Пример #8
0
func TestLoadSketchFromFolder(t *testing.T) {
	context := make(map[string]interface{})
	context[constants.CTX_SKETCH_LOCATION] = "sketch_with_subfolders"

	commands := []types.Command{
		&builder.SetupHumanLoggerIfMissing{},
		&builder.SketchLoader{},
	}

	for _, command := range commands {
		err := command.Run(context)
		NoError(t, err)
	}

	sketch := context[constants.CTX_SKETCH].(*types.Sketch)
	require.NotNil(t, sketch)

	require.Contains(t, sketch.MainFile.Name, "sketch_with_subfolders.ino")

	require.Equal(t, 0, len(sketch.OtherSketchFiles))

	require.Equal(t, 2, len(sketch.AdditionalFiles))
	require.Contains(t, sketch.AdditionalFiles[0].Name, "other.cpp")
	require.Contains(t, sketch.AdditionalFiles[1].Name, "other.h")
}
Пример #9
0
// If there is more than one key, removeKeyInteractively will ask which key to
// delete.  Then it will confirm whether they want to delete, and the user can
// abort at that confirmation.
func TestRemoveMultikeysAbortChoice(t *testing.T) {
	setUp(t)
	in := bytes.NewBuffer([]byte("1\nn\n"))

	key, err := trustmanager.GenerateED25519Key(rand.Reader)
	require.NoError(t, err)

	stores := []trustmanager.KeyStore{
		trustmanager.NewKeyMemoryStore(ret),
		trustmanager.NewKeyMemoryStore(ret),
	}

	err = stores[0].AddKey(trustmanager.KeyInfo{Role: data.CanonicalRootRole, Gun: ""}, key)
	require.NoError(t, err)

	err = stores[1].AddKey(trustmanager.KeyInfo{Role: data.CanonicalTargetsRole, Gun: "gun"}, key)
	require.NoError(t, err)

	var out bytes.Buffer

	err = removeKeyInteractively(stores, key.ID(), in, &out)
	require.NoError(t, err) // no error to abort deleting
	text, err := ioutil.ReadAll(&out)
	require.NoError(t, err)

	require.Len(t, stores[0].ListKeys(), 1)
	require.Len(t, stores[1].ListKeys(), 1)

	// It should have listed the keys, asked whether the user really wanted to
	// delete, and then aborted.
	output := string(text)
	require.Contains(t, output, "Found the following matching keys")
	require.Contains(t, output, "Are you sure")
	require.Contains(t, output, "Aborting action")
}
Пример #10
0
// If there is one key, asking to remove it will ask for confirmation.  Passing
// 'yes'/'y' response will continue the deletion.
func TestRemoveOneKeyConfirm(t *testing.T) {
	setUp(t)
	yesses := []string{"yes", " Y "}

	for _, yesAnswer := range yesses {
		store := trustmanager.NewKeyMemoryStore(ret)

		key, err := trustmanager.GenerateED25519Key(rand.Reader)
		require.NoError(t, err)
		err = store.AddKey(trustmanager.KeyInfo{Role: data.CanonicalRootRole, Gun: ""}, key)
		require.NoError(t, err)

		var out bytes.Buffer
		in := bytes.NewBuffer([]byte(yesAnswer + "\n"))

		err = removeKeyInteractively(
			[]trustmanager.KeyStore{store}, key.ID(), in, &out)
		require.NoError(t, err)
		text, err := ioutil.ReadAll(&out)
		require.NoError(t, err)

		output := string(text)
		require.Contains(t, output, "Are you sure")
		require.Contains(t, output, "Deleted "+key.ID())
		require.Len(t, store.ListKeys(), 0)
	}
}
Пример #11
0
func TestResExtensionsEmptyQuote(t *testing.T) {
	cd, err := ParseResponseCacheControl(`foo="" bar="hi"`)
	require.NoError(t, err)
	require.Equal(t, cd.SMaxAge, DeltaSeconds(-1))
	require.Equal(t, len(cd.Extensions), 2)
	require.Contains(t, cd.Extensions, "bar=hi")
	require.Contains(t, cd.Extensions, "foo=")
}
Пример #12
0
func TestThriftNilErr(t *testing.T) {
	var thriftErr *gen.SimpleErr
	withSetup(t, func(ctx Context, args testArgs) {
		args.s1.On("Simple", ctxArg()).Return(thriftErr)
		got := args.c1.Simple(ctx)
		require.Error(t, got)
		require.Contains(t, got.Error(), "non-nil error type")
		require.Contains(t, got.Error(), "nil value")
	})
}
Пример #13
0
func TestErrServerUnavailable(t *testing.T) {
	for i := 200; i < 600; i++ {
		err := ErrServerUnavailable{code: i}
		if i == 401 {
			require.Contains(t, err.Error(), "not authorized")
		} else {
			require.Contains(t, err.Error(), "unable to reach trust server")
		}
	}
}
Пример #14
0
func TestApplyTargetsDelegationAlreadyExistingMergePaths(t *testing.T) {
	repo, cs, err := testutils.EmptyRepo("docker.com/notary")
	require.NoError(t, err)

	newKey, err := cs.Create("targets/level1", "docker.com/notary", data.ED25519Key)
	require.NoError(t, err)

	// create delegation
	kl := data.KeyList{newKey}
	td := &changelist.TUFDelegation{
		NewThreshold: 1,
		AddKeys:      kl,
		AddPaths:     []string{"level1"},
	}

	tdJSON, err := json.Marshal(td)
	require.NoError(t, err)

	ch := changelist.NewTUFChange(
		changelist.ActionCreate,
		"targets/level1",
		changelist.TypeTargetsDelegation,
		"",
		tdJSON,
	)

	err = applyTargetsChange(repo, nil, ch)
	require.NoError(t, err)
	// we have sufficient checks elsewhere we don't need to confirm that
	// creating fresh works here via more requires.

	// Use different path for this changelist
	td.AddPaths = []string{"level2"}

	tdJSON, err = json.Marshal(td)
	require.NoError(t, err)

	ch = changelist.NewTUFChange(
		changelist.ActionCreate,
		"targets/level1",
		changelist.TypeTargetsDelegation,
		"",
		tdJSON,
	)

	// when attempting to create the same role again, check that we
	// merged with previous details
	err = applyTargetsChange(repo, nil, ch)
	require.NoError(t, err)
	delegation, err := repo.GetDelegationRole("targets/level1")
	require.NoError(t, err)
	// Assert we have both paths
	require.Contains(t, delegation.Paths, "level2")
	require.Contains(t, delegation.Paths, "level1")
}
Пример #15
0
func TestReqExtensions(t *testing.T) {
	cd, err := ParseRequestCacheControl(`min-fresh=99999 foobar=1 cats`)
	require.NoError(t, err)
	require.NotNil(t, cd)
	require.Equal(t, cd.MinFresh, DeltaSeconds(99999))
	require.Equal(t, cd.MaxAge, DeltaSeconds(-1))
	require.Equal(t, cd.MaxStale, DeltaSeconds(-1))
	require.Len(t, cd.Extensions, 2)
	require.Contains(t, cd.Extensions, "foobar=1")
	require.Contains(t, cd.Extensions, "cats")
}
Пример #16
0
func Test(t *testing.T) {
	// should be valid
	bitriseConfContent, warnings, err := generateBitriseYMLContent("App Title", "master")
	require.NoError(t, err)
	require.Equal(t, 0, len(warnings))
	require.NotEqual(t, "", bitriseConfContent)
	require.Contains(t, bitriseConfContent, fmt.Sprintf("format_version: %s", models.Version))
	require.Contains(t, bitriseConfContent, `- BITRISE_APP_TITLE: "App Title"`)
	require.Contains(t, bitriseConfContent, `- BITRISE_DEV_BRANCH: "master"`)

	_, warnings, err = bitrise.ConfigModelFromYAMLBytes([]byte(bitriseConfContent))
	require.NoError(t, err)
	require.Equal(t, 0, len(warnings))
}
Пример #17
0
func TestInsert(t *testing.T) {
	c, _ := newTestCache()

	// Insert normal
	oldestTok, err := c.Insert(nextRequest())
	require.NoError(t, err)
	assert.Len(t, oldestTok, TokenLen)
	assertCacheSize(t, c, 1)

	// Insert until full
	for i := 0; i < MaxInFlight-2; i++ {
		tok, err := c.Insert(nextRequest())
		require.NoError(t, err)
		assert.Len(t, tok, TokenLen)
	}
	assertCacheSize(t, c, MaxInFlight-1)

	newestReq := nextRequest()
	newestTok, err := c.Insert(newestReq)
	require.NoError(t, err)
	assert.Len(t, newestTok, TokenLen)
	assertCacheSize(t, c, MaxInFlight)
	require.Contains(t, c.tokens, oldestTok, "oldest request should still be cached")

	// Consume newest token.
	req, ok := c.Consume(newestTok)
	assert.True(t, ok, "newest request should still be cached")
	assert.Equal(t, newestReq, req)
	require.Contains(t, c.tokens, oldestTok, "oldest request should still be cached")

	// Insert again (still full)
	tok, err := c.Insert(nextRequest())
	require.NoError(t, err)
	assert.Len(t, tok, TokenLen)
	assertCacheSize(t, c, MaxInFlight)

	// Insert again (should evict)
	_, err = c.Insert(nextRequest())
	assert.Error(t, err, "should reject further requests")
	errResponse := httptest.NewRecorder()
	require.NoError(t, WriteError(err, errResponse))
	assert.Equal(t, errResponse.Code, http.StatusTooManyRequests)
	assert.Equal(t, strconv.Itoa(int(CacheTTL.Seconds())), errResponse.HeaderMap.Get("Retry-After"))

	assertCacheSize(t, c, MaxInFlight)
	_, ok = c.Consume(oldestTok)
	assert.True(t, ok, "oldest request should be valid")
}
Пример #18
0
func TestLogBrokerNoFollowUnscheduledTask(t *testing.T) {
	ctx, ca, _, serverAddr, _, done := testLogBrokerEnv(t)
	defer done()

	client, clientDone := testLogClient(t, serverAddr)
	defer clientDone()

	// Create fake environment.
	require.NoError(t, ca.MemoryStore.Update(func(tx store.Tx) error {
		return store.CreateTask(tx, &api.Task{
			ID:        "task1",
			ServiceID: "service",
		})
	}))

	// Subscribe to logs in no follow mode
	logs, err := client.SubscribeLogs(ctx, &api.SubscribeLogsRequest{
		Options: &api.LogSubscriptionOptions{
			Follow: false,
		},
		Selector: &api.LogSelector{
			ServiceIDs: []string{"service"},
		},
	})
	require.NoError(t, err)

	// Ensure we receive the message that we could grab
	_, err = logs.Recv()
	require.Error(t, err)
	require.Contains(t, err.Error(), "task1 has not been scheduled")
}
Пример #19
0
// If encryption fails, saving will fail
func TestSaveEncryptionFails(t *testing.T) {
	metadata, entries, snapshot := makeWALData(1, 1)

	tempdir, err := ioutil.TempDir("", "waltests")
	require.NoError(t, err)
	os.RemoveAll(tempdir)
	defer os.RemoveAll(tempdir)

	// fail encrypting one of the entries, but not the first one
	c := NewWALFactory(&meowCrypter{encryptFailures: map[string]struct{}{
		"Entry 3": {},
	}}, nil)
	wrapped, err := c.Create(tempdir, metadata)
	require.NoError(t, err)

	require.NoError(t, wrapped.SaveSnapshot(snapshot))
	err = wrapped.Save(raftpb.HardState{}, entries)
	require.Error(t, err)
	require.Contains(t, err.Error(), "refusing to encrypt")
	require.NoError(t, wrapped.Close())

	// no entries are written at all
	ogWAL, err := OriginalWAL.Open(tempdir, snapshot)
	require.NoError(t, err)
	defer ogWAL.Close()

	_, _, ents, err := ogWAL.ReadAll()
	require.NoError(t, err)
	require.Empty(t, ents)
}
Пример #20
0
// If one of the specified pkcs11 functions errors, the function under test
// will clean up after itself
func testYubiFunctionCleansUpOnSpecifiedErrors(t *testing.T,
	toStub pkcs11Stubbable, functionUnderTest func() error,
	dependentFunctions []string, functionShouldError bool) {

	for _, methodName := range dependentFunctions {

		toStub.setLibLoader(func(string) IPKCS11Ctx {
			return NewStubCtx(
				map[string]bool{methodName: true})
		})

		err := functionUnderTest()
		if functionShouldError {
			require.Error(t, err,
				fmt.Sprintf("Didn't error when %s errored.", methodName))
			// a lot of these functions wrap other errors
			require.Contains(t, err.Error(), errInjected{methodName}.Error())
		} else {
			require.NoError(t, err)
		}
	}

	// Set Up another time, to ensure we weren't left in a bad state
	// by the previous runs
	ctx, session, err := SetupHSMEnv(pkcs11Lib, defaultLoader)
	require.NoError(t, err)
	cleanup(ctx, session)
}
Пример #21
0
func TestExecFalse(t *testing.T) {
	check := NewCheckExec()
	check.Command = []string{"/bin/false"}
	require.NoError(t, check.Init(&Service{nerve: &Nerve{}}))

	require.Contains(t, check.Check().Error(), "Command failed")
}
Пример #22
0
// If decrypting a snapshot fails, the error is propagated
func TestSnapshotterLoadDecryptingFail(t *testing.T) {
	tempdir, err := ioutil.TempDir("", "snapwrap")
	require.NoError(t, err)
	defer os.RemoveAll(tempdir)

	crypter := &meowCrypter{}

	ogSnap := OriginalSnap.New(tempdir)
	r := api.MaybeEncryptedRecord{
		Data:      fakeSnapshotData.Data,
		Algorithm: crypter.Algorithm(),
	}
	data, err := r.Marshal()
	require.NoError(t, err)

	emptyEncryptionFakeData := fakeSnapshotData
	emptyEncryptionFakeData.Data = data

	require.NoError(t, ogSnap.SaveSnap(emptyEncryptionFakeData))

	c := NewSnapFactory(encryption.NoopCrypter, crypter)
	wrapped := c.New(tempdir)

	_, err = wrapped.Load()
	require.Error(t, err)
	require.Contains(t, err.Error(), "not meowcoded")
}
Пример #23
0
func TestSendUnreachable(t *testing.T) {
	ctx, cancel := context.WithCancel(context.Background())
	c := newCluster()
	defer func() {
		cancel()
		c.Stop()
	}()
	require.NoError(t, c.Add(1))
	require.NoError(t, c.Add(2))

	// set channel to nil to emulate full queue
	// we need to reset some fields after cancel
	p2 := c.Get(1).tr.peers[2]
	p2.cancel()
	<-p2.done
	p2.msgc = nil
	p2.done = make(chan struct{})
	p2.ctx = ctx
	go p2.run(ctx)

	msgCtx, msgCancel := context.WithTimeout(ctx, 4*time.Second)
	defer msgCancel()

	err := sendMessages(msgCtx, c, 1, []uint64{2}, raftpb.MsgSnap)
	require.Error(t, err)
	require.Contains(t, err.Error(), "peer is unreachable")
	select {
	case id := <-c.Get(1).reportedUnreachables:
		assert.Equal(t, id, uint64(2))
	case <-msgCtx.Done():
		t.Fatal(ctx.Err())
	}
}
Пример #24
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"))
}
Пример #25
0
// insufficient arguments produce an error before any parsing of configs happens
func TestInsufficientArgumentsReturnsErrorAndPrintsUsage(t *testing.T) {
	tempdir, err := ioutil.TempDir("", "empty-dir")
	require.NoError(t, err)
	defer os.RemoveAll(tempdir)

	for _, args := range exampleValidCommands {
		b := new(bytes.Buffer)
		cmd := NewNotaryCommand()
		cmd.SetOutput(b)

		arglist := strings.Fields(args)
		if args == "key list" || args == "key generate rsa" {
			// in these case, "key" or "key generate" are valid commands, so add an arg to them instead
			arglist = append(arglist, "extraArg")
		} else {
			arglist = arglist[:len(arglist)-1]
		}

		invalid := strings.Join(arglist, " ")

		cmd.SetArgs(append(
			[]string{"-c", filepath.Join(tempdir, "idonotexist.json"), "-d", tempdir}, arglist...))
		err = cmd.Execute()

		require.NotContains(t, err.Error(), "error opening config file", "running `notary %s`", invalid)
		// it's a usage error, so the usage is printed
		require.Contains(t, b.String(), "Usage:", "expected usage when running `notary %s`", invalid)
	}
}
Пример #26
0
// Non-roles and delegation keys can't be rotated with the command line
func TestRotateKeyInvalidRoles(t *testing.T) {
	setUp(t)
	invalids := []string{
		"notevenARole",
		"targets/a",
	}
	for _, role := range invalids {
		for _, serverManaged := range []bool{true, false} {
			k := &keyCommander{
				configGetter:           func() (*viper.Viper, error) { return viper.New(), nil },
				getRetriever:           func() notary.PassRetriever { return passphrase.ConstantRetriever("pass") },
				rotateKeyRole:          role,
				rotateKeyServerManaged: serverManaged,
			}
			commands := []string{"gun", role}
			if serverManaged {
				commands = append(commands, "-r")
			}
			err := k.keysRotate(&cobra.Command{}, commands)
			require.Error(t, err)
			require.Contains(t, err.Error(),
				fmt.Sprintf("does not currently permit rotating the %s key", role))
		}
	}
}
Пример #27
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")
}
Пример #28
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))
}
Пример #29
0
// Invalid key algorithms result in an error if a remote trust service was
// specified.
func TestGetTrustServiceInvalidKeyAlgorithm(t *testing.T) {
	configTemplate := `
	{
		"trust_service": {
			"type": "remote",
			"hostname": "blah",
			"port": "1234",
			"key_algorithm": "%s"
		}
	}`
	badKeyAlgos := []string{
		fmt.Sprintf(configTemplate, ""),
		fmt.Sprintf(configTemplate, data.ECDSAx509Key),
		fmt.Sprintf(configTemplate, "random"),
	}
	var registerCalled = 0

	for _, config := range badKeyAlgos {
		_, _, err := getTrustService(configure(config),
			client.NewNotarySigner, fakeRegisterer(&registerCalled))
		require.Error(t, err)
		require.Contains(t, err.Error(), "invalid key algorithm")
	}
	// no health function ever registered
	require.Equal(t, 0, registerCalled)
}
Пример #30
0
func TestPacProxyReturnsNilURLAndErrorForProxyResultWhenConnectionFails(t *testing.T) {
	p, e := NewPac()
	require.NoError(t, e)
	require.NoError(t, p.Load(`
function FindProxyForURL(url, host)
{
	return "PROXY 127.0.0.1:9";
}`))
	in, _ := url.Parse("http://example.com:82/foo")
	out, e := p.Proxy(in)
	require.Error(t, e)
	require.Nil(t, out)
	require.Contains(t, e.Error(), "Unable to process FindProxyForURL(\"http://example.com:82/foo\", \"example.com\") result \"PROXY 127.0.0.1:9\".\nConnection to \"127.0.0.1:9\" is currently blacklisted for 4m59s:")
	require.Contains(t, e.Error(), "127.0.0.1:9")
	require.Contains(t, e.Error(), "connection refused.")
}