Beispiel #1
0
func TestAbsPath(t *testing.T) {
	// should expand path

	currDirPath, err := filepath.Abs(".")
	require.Equal(t, nil, err)
	require.NotEqual(t, "", currDirPath)
	require.NotEqual(t, ".", currDirPath)

	homePathEnv := "/path/home/test-user"
	require.Equal(t, nil, os.Setenv("HOME", homePathEnv))

	testFileRelPathFromHome := "some/file.ext"
	absPathToTestFile := fmt.Sprintf("%s/%s", homePathEnv, testFileRelPathFromHome)

	expandedPath, err := AbsPath("")
	require.NotEqual(t, nil, err)
	require.Equal(t, "", expandedPath)

	expandedPath, err = AbsPath(".")
	require.Equal(t, nil, err)
	require.Equal(t, currDirPath, expandedPath)

	expandedPath, err = AbsPath(fmt.Sprintf("$HOME/%s", testFileRelPathFromHome))
	require.Equal(t, nil, err)
	require.Equal(t, absPathToTestFile, expandedPath)

	expandedPath, err = AbsPath(fmt.Sprintf("~/%s", testFileRelPathFromHome))
	require.Equal(t, nil, err)
	require.Equal(t, absPathToTestFile, expandedPath)
}
func TestValidate(t *testing.T) {
	// No key-value
	env := EnvironmentItemModel{
		OptionsKey: 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(true),
			IsDontChangeValue: pointers.NewBoolPtr(false),
		},
	}
	require.NotEqual(t, nil, env.Validate())

	// Empty key
	env = EnvironmentItemModel{
		"": "test_value",
	}
	require.NotEqual(t, nil, env.Validate())

	// Valid env
	env = EnvironmentItemModel{
		"test_key": "test_value",
	}
	require.Equal(t, nil, env.Validate())
}
Beispiel #3
0
func TestParseMutationAndQuery(t *testing.T) {
	query := `
		mutation {
			set {
				<name> <is> <something> .
				<hometown> <is> <san francisco> .
			}
			delete {
				<name> <is> <something-else> .
			}
		}
		query {
			me(_xid_: tomhanks) {
				name
				hometown
			}
		}
	`
	gq, mu, err := Parse(query)
	require.NoError(t, err)
	require.NotNil(t, mu)
	require.NotEqual(t, strings.Index(mu.Set, "<name> <is> <something> ."), -1)
	require.NotEqual(t, strings.Index(mu.Set, "<hometown> <is> <san francisco> ."), -1)
	require.NotEqual(t, strings.Index(mu.Del, "<name> <is> <something-else> ."), -1)

	require.NotNil(t, gq)
	require.Equal(t, gq.XID, "tomhanks")
	require.Equal(t, childAttrs(gq), []string{"name", "hometown"})
}
func TestBumpVersion(t *testing.T) {
	version, err := bumpedVersion("", 0)
	require.NotEqual(t, nil, err)
	require.Equal(t, "", version)

	version, err = bumpedVersion("-1", 0)
	require.NotEqual(t, nil, err)
	require.Equal(t, "", version)

	version, err = bumpedVersion("1", 0)
	require.Equal(t, nil, err)
	require.Equal(t, "2.0.0", version)

	version, err = bumpedVersion("1.1", 0)
	require.Equal(t, nil, err)
	require.Equal(t, "2.1.0", version)

	version, err = bumpedVersion("1.1", 1)
	require.Equal(t, nil, err)
	require.Equal(t, "1.2.0", version)

	version, err = bumpedVersion("1.1.1", 0)
	require.Equal(t, nil, err)
	require.Equal(t, "2.1.1", version)

	version, err = bumpedVersion("1.1.1", 1)
	require.Equal(t, nil, err)
	require.Equal(t, "1.2.1", version)

	version, err = bumpedVersion("1.1.1", 2)
	require.Equal(t, nil, err)
	require.Equal(t, "1.1.2", version)
}
Beispiel #5
0
func TestCreateKeyCreatesNewKeys(t *testing.T) {
	publicKey1, err := kmClient.CreateKey(context.Background(), &pb.Algorithm{Algorithm: data.ED25519Key})
	require.Nil(t, err)
	publicKey2, err := kmClient.CreateKey(context.Background(), &pb.Algorithm{Algorithm: data.ED25519Key})
	require.Nil(t, err)
	require.NotEqual(t, publicKey1, publicKey2)
	require.NotEqual(t, publicKey1.KeyInfo, publicKey2.KeyInfo)
	require.NotEqual(t, publicKey1.PublicKey, publicKey2.PublicKey)
}
Beispiel #6
0
// Verifies that the body is as expected  and that there are cache control headers
func verifyGetResponse(t *testing.T, r *http.Response, expectedBytes []byte) {
	body, err := ioutil.ReadAll(r.Body)
	require.NoError(t, err)
	require.True(t, bytes.Equal(expectedBytes, body))

	require.NotEqual(t, "", r.Header.Get("Cache-Control"))
	require.NotEqual(t, "", r.Header.Get("Last-Modified"))
	require.Equal(t, "", r.Header.Get("Pragma"))
}
Beispiel #7
0
func TestRotateWithCompression(t *testing.T) {
	f, err := ioutil.TempFile(os.TempDir(), "logr")
	require.Nil(t, err)

	rw, err := logr.NewWriterFromFileWithCompression(f)
	require.Nil(t, err)

	// add some clear text at the beginning of the file
	text := []byte("This is some clear test at the beginning of the file.")

	now := time.Now()
	{
		n, err := rw.Write(text)
		require.Nil(t, err)
		require.Equal(t, len(text), n)

		n, err = rw.Write(makeBuf(0xFF))
		require.Nil(t, err)
		require.Equal(t, 1024, n)

		rw.MaxSize(512)

		n, err = rw.Write(makeBuf(0xFE))
		require.Nil(t, err)
		require.Equal(t, 1024, n)
	}

	newData := readFile(t, f.Name())
	require.Nil(t, checkEqual(t, newData, 0xFE))

	{
		f, err := os.Open(f.Name() + "." + now.Format(logr.TimeFormat) + ".gz")
		require.Nil(t, err)
		require.NotNil(t, f)

		rotatedDataGz, err := ioutil.ReadAll(f)
		require.Nil(t, err)
		require.NotEqual(t, 0, len(rotatedDataGz))

		// should not be equal cause it has been gzipped
		require.NotEqual(t, text, rotatedDataGz[:len(text)])

		// gunzip
		r, err := gzip.NewReader(bytes.NewReader(rotatedDataGz))
		require.Nil(t, err)

		gunzip, err := ioutil.ReadAll(r)
		require.Nil(t, err)

		// should be equal cause now gunzipped
		require.Equal(t, text, gunzip[:len(text)])
	}
}
Beispiel #8
0
func TestStepmanJSONStepLibStepInfo(t *testing.T) {
	// Valid params -- Err should empty, output filled
	require.Equal(t, nil, StepmanSetup("https://github.com/bitrise-io/bitrise-steplib"))

	outStr, err := StepmanJSONStepLibStepInfo("https://github.com/bitrise-io/bitrise-steplib", "script", "0.9.0")
	require.Equal(t, nil, err)
	require.NotEqual(t, "", outStr)

	// Invalid params -- Err should empty, output filled
	outStr, err = StepmanJSONStepLibStepInfo("https://github.com/bitrise-io/bitrise-steplib", "script", "2")
	require.NotEqual(t, nil, err)
	require.Equal(t, "", outStr)
}
Beispiel #9
0
func TestMarshalEncoder(t *testing.T) {
	record := newLogFFRecord()
	out := bytes.Buffer{}
	enc := ffjson.NewEncoder(&out)
	err := enc.Encode(record)
	require.NoError(t, err)
	require.NotEqual(t, 0, out.Len(), "encoded buffer size should not be 0")

	out.Reset()
	err = enc.EncodeFast(record)
	require.NoError(t, err)
	require.NotEqual(t, 0, out.Len(), "encoded buffer size should not be 0")
}
Beispiel #10
0
// This changes the root key
func TestSwizzlerChangeRootKey(t *testing.T) {
	f, origMeta := createNewSwizzler(t)

	f.ChangeRootKey()

	tufRepo := tuf.NewRepo(f.CryptoService)

	// we want to test these in a specific order
	roles := []string{data.CanonicalRootRole, data.CanonicalTargetsRole, data.CanonicalSnapshotRole,
		data.CanonicalTimestampRole, "targets/a", "targets/a/b"}

	for _, role := range roles {
		origMeta := origMeta[role]
		newMeta, err := f.MetadataCache.GetMeta(role, -1)
		require.NoError(t, err)

		// the threshold for base roles is set in root
		switch role {
		case data.CanonicalRootRole:
			require.False(t, bytes.Equal(origMeta, newMeta))
			origRoot, newRoot := &data.SignedRoot{}, &data.SignedRoot{}
			require.NoError(t, json.Unmarshal(origMeta, origRoot))
			require.NoError(t, json.Unmarshal(newMeta, newRoot))

			require.NotEqual(t, len(origRoot.Signed.Keys), len(newRoot.Signed.Keys))

			var rootRole data.Role
			for r, origRole := range origRoot.Signed.Roles {
				newRole := newRoot.Signed.Roles[r]
				require.Len(t, origRole.KeyIDs, 1)
				require.Len(t, newRole.KeyIDs, 1)
				if r == data.CanonicalRootRole {
					require.NotEqual(t, origRole.KeyIDs[0], newRole.KeyIDs[0])
					rootRole = data.Role{RootRole: *newRole, Name: data.CanonicalRootRole}
				} else {
					require.Equal(t, origRole.KeyIDs[0], newRole.KeyIDs[0])
				}
			}

			require.NoError(t, tufRepo.SetRoot(newRoot))
			signedThing, err := newRoot.ToSigned()
			require.NoError(t, err)
			newKey := newRoot.Signed.Keys[rootRole.KeyIDs[0]]
			require.NoError(t, signed.Verify(signedThing,
				data.BaseRole{Name: data.CanonicalRootRole, Keys: map[string]data.PublicKey{newKey.ID(): newKey}, Threshold: 1}, 1))
		default:
			require.True(t, bytes.Equal(origMeta, newMeta), "bytes have changed for role %s", role)
		}
	}
}
Beispiel #11
0
func TestShortIDPropagation(t *testing.T) {
	_, peers1 := newNode(PeerName(1))
	_, peers2 := newNode(PeerName(2))

	peers1.AddTestConnection(peers2.ourself.Peer)
	peers1.applyUpdate(peers2.encodePeers(peers2.names()))
	peers12 := peers1.Fetch(PeerName(2))
	old := peers12.peerSummary

	require.True(t,
		peers2.reassignLocalShortID(&peersPendingNotifications{}))
	peers1.applyUpdate(peers2.encodePeers(peers2.names()))
	require.NotEqual(t, old.Version, peers12.Version)
	require.NotEqual(t, old.ShortID, peers12.ShortID)
}
Beispiel #12
0
// GetTileStoreFromEnv looks at the TEST_TILE_DIR environement variable for the
// name of directory that contains tiles. If it's defined it will return a
// TileStore instance. If the not the calling test will fail.
func GetTileStoreFromEnv(t assert.TestingT) tiling.TileStore {
	// Get the TEST_TILE environment variable that points to the
	// tile to read.
	tileDir := os.Getenv("TEST_TILE_DIR")
	assert.NotEqual(t, "", tileDir, "Please define the TEST_TILE_DIR environment variable to point to a live tile store.")
	return filetilestore.NewFileTileStore(tileDir, config.DATASET_GOLD, 2*time.Minute)
}
Beispiel #13
0
func deleteBad(t *testing.T, ctx *Context) {
	fmt.Println("deleteBad")
	require.NotEqual(t, ctx.mountPath, "", "Device is not mounted")

	err := ctx.Delete(ctx.volID)
	require.Error(t, err, "Delete on mounted device must fail")
}
Beispiel #14
0
// This rotates the key of some base role
func TestSwizzlerRotateKeyBaseRole(t *testing.T) {
	f, origMeta := createNewSwizzler(t)

	theRole := data.CanonicalSnapshotRole
	cs := signed.NewEd25519()
	pubKey, err := cs.Create(theRole, f.Gun, data.ED25519Key)
	require.NoError(t, err)

	require.NoError(t, f.RotateKey(theRole, pubKey))

	for role, metaBytes := range origMeta {
		newMeta, err := f.MetadataCache.GetSized(role, store.NoSizeLimit)
		require.NoError(t, err)

		if role != data.CanonicalRootRole {
			require.True(t, bytes.Equal(metaBytes, newMeta), "bytes have changed for role %s", role)
		} else {
			require.False(t, bytes.Equal(metaBytes, newMeta))
			origSigned, newSigned := &data.SignedRoot{}, &data.SignedRoot{}
			require.NoError(t, json.Unmarshal(metaBytes, origSigned))
			require.NoError(t, json.Unmarshal(newMeta, newSigned))
			require.NotEqual(t, []string{pubKey.ID()}, origSigned.Signed.Roles[theRole].KeyIDs)
			require.Equal(t, []string{pubKey.ID()}, newSigned.Signed.Roles[theRole].KeyIDs)
			_, ok := origSigned.Signed.Keys[pubKey.ID()]
			require.False(t, ok)
			_, ok = newSigned.Signed.Keys[pubKey.ID()]
			require.True(t, ok)
		}
	}
}
Beispiel #15
0
func TestNewLexerMutation(t *testing.T) {
	input := `
	mutation {
		set {
			What is <this> .
			Why is this #!!?
			How is this?
		}
		delete {
			Why is this
		}
	}
	query {
		me(_xid_: rick) {
			_city
		}
	}`
	l := &lex.Lexer{}
	l.Init(input)
	go run(l)
	for item := range l.Items {
		require.NotEqual(t, item.Typ, lex.ItemError)
		t.Log(item.String())
	}
}
Beispiel #16
0
// Using the same key to encrypt the same message, this encrypter produces two
// different ciphertexts because it produces two different nonces.  Both
// of these can be decrypted into the same data though.
func TestNACLSecretbox(t *testing.T) {
	key := make([]byte, 32)
	_, err := io.ReadFull(rand.Reader, key)
	require.NoError(t, err)

	crypter := NewNACLSecretbox(key)
	data := []byte("Hello again world")

	er1, err := crypter.Encrypt(data)
	require.NoError(t, err)

	er2, err := crypter.Encrypt(data)
	require.NoError(t, err)

	require.NotEqual(t, er1.Data, er2.Data)
	require.NotEmpty(t, er1.Nonce, er2.Nonce)

	result, err := crypter.Decrypt(*er1)
	require.NoError(t, err)
	require.Equal(t, data, result)

	result, err = crypter.Decrypt(*er2)
	require.NoError(t, err)
	require.Equal(t, data, result)
}
Beispiel #17
0
// Perform a DNS query and assert the reply code, number or answers, etc
func assertExchange(t *testing.T, z string, ty uint16, port int, minAnswers int, maxAnswers int, expErr int) (*dns.Msg, *dns.Msg) {
	require.NotEqual(t, 0, port, "invalid DNS server port")

	c := &dns.Client{
		UDPSize: testUDPBufSize,
	}

	m := new(dns.Msg)
	m.RecursionDesired = true
	m.SetQuestion(z, ty)
	m.SetEdns0(testUDPBufSize, false) // we don't want to play with truncation here...

	lstAddr := fmt.Sprintf("127.0.0.1:%d", port)
	r, _, err := c.Exchange(m, lstAddr)
	t.Logf("Response from '%s':\n%+v\n", lstAddr, r)
	if err != nil {
		t.Errorf("Error when querying DNS server at %s: %s", lstAddr, err)
	}
	require.NoError(t, err)
	if minAnswers == 0 && maxAnswers == 0 {
		require.Equal(t, expErr, r.Rcode, "DNS response code")
	} else {
		require.Equal(t, dns.RcodeSuccess, r.Rcode, "DNS response code")
	}
	answers := len(r.Answer)
	if minAnswers >= 0 && answers < minAnswers {
		require.FailNow(t, fmt.Sprintf("Number of answers >= %d", minAnswers))
	}
	if maxAnswers >= 0 && answers > maxAnswers {
		require.FailNow(t, fmt.Sprintf("Number of answers <= %d", maxAnswers))
	}
	return m, r
}
Beispiel #18
0
func testStoreFeatures(t *testing.T, store Store) {
	// it should failt to get a feature that doesn't exist
	found, err := store.GetFeatureByName("awesome_feature")
	require.Equal(t, ErrNoRows, err)

	// it should get an empty list when there is no features
	list, err := store.ListFeatures()
	require.NoError(t, err)
	require.Empty(t, list)

	// it should create a feature
	feature := &models.Feature{
		Name: "awesome_feature",
	}

	err = store.CreateFeature(feature)
	require.NoError(t, err)
	require.NotEqual(t, feature.ID, 0)
	require.Equal(t, "awesome_feature", feature.Name)
	require.Empty(t, feature.Status)

	// it should update a feature
	feature.Name = "not_awesome_feature"

	err = store.UpdateFeature(feature)
	require.NoError(t, err)

	// it should list all features
	list, err = store.ListFeatures()
	require.NoError(t, err)
	require.Len(t, list, 1)

	// it should get a feature with the status of all environments
	err = store.CreateEnvironment(&models.Environment{
		Name: "staging",
	})
	require.NoError(t, err)

	found, err = store.GetFeatureByName("not_awesome_feature")
	require.NoError(t, err)
	require.Len(t, found.Status, 1)
	require.Equal(t, false, found.Status["staging"])

	// it should update the status of a feature in an environment
	found.Status["staging"] = true

	err = store.UpdateFeature(found)
	require.NoError(t, err)

	found, err = store.GetFeatureByName("not_awesome_feature")
	require.NoError(t, err)
	require.Equal(t, true, found.Status["staging"])

	// it should list all features with the status on all environments
	list, err = store.ListFeatures()
	require.NoError(t, err)
	require.Len(t, list, 1)
	require.Equal(t, found.ID, list[0].ID)
	require.True(t, list[0].Status["staging"])
}
Beispiel #19
0
func TestLockFileReadAndUnlockFile(t *testing.T) {
	// Create a temporary file
	tmpDir, err := ioutil.TempDir("", "TestLockFileReadAndUnlockFile")
	defer os.RemoveAll(tmpDir)
	require.Nil(t, err)
	require.NotEqual(t, "", tmpDir)

	// Create the dummy file, and open it for reading
	file1 := filepath.Join(tmpDir, "file1")
	ioutil.WriteFile(file1, []byte("123"), 0700)
	file, err := os.Open(file1)
	require.Nil(t, err)

	// We opened the file read-only, so trying to get a write lock should result in an error
	assert.NotNil(t, LockFile(file, Write))

	// Get the read lock
	assert.Nil(t, LockFile(file, Read))

	// Make sure that we hold a proper lock to the file
	locked, err := isLocked(file1, "READ")
	assert.Nil(t, err)
	assert.True(t, locked)

	// // Unlock the file again
	assert.Nil(t, UnlockFile(file))

	// Make sure that we no longer hold the lock
	locked, err = isLocked(file1, "READ")
	assert.Nil(t, err)
	assert.False(t, locked)

	file.Close()
}
Beispiel #20
0
// This rotates the key of some delegation role
func TestSwizzlerRotateKeyDelegationRole(t *testing.T) {
	f, origMeta := createNewSwizzler(t)

	theRole := "targets/a/b"
	cs := signed.NewEd25519()
	pubKey, err := cs.Create(theRole, f.Gun, data.ED25519Key)
	require.NoError(t, err)

	require.NoError(t, f.RotateKey(theRole, pubKey))

	for role, metaBytes := range origMeta {
		newMeta, err := f.MetadataCache.GetMeta(role, store.NoSizeLimit)
		require.NoError(t, err)

		if role != "targets/a" {
			require.True(t, bytes.Equal(metaBytes, newMeta), "bytes have changed for role %s", role)
		} else {
			require.False(t, bytes.Equal(metaBytes, newMeta))
			origSigned, newSigned := &data.SignedTargets{}, &data.SignedTargets{}
			require.NoError(t, json.Unmarshal(metaBytes, origSigned))
			require.NoError(t, json.Unmarshal(newMeta, newSigned))
			require.NotEqual(t, []string{pubKey.ID()}, origSigned.Signed.Delegations.Roles[0].KeyIDs)
			require.Equal(t, []string{pubKey.ID()}, newSigned.Signed.Delegations.Roles[0].KeyIDs)
			_, ok := origSigned.Signed.Delegations.Keys[pubKey.ID()]
			require.False(t, ok)
			_, ok = newSigned.Signed.Delegations.Keys[pubKey.ID()]
			require.True(t, ok)
		}
	}
}
Beispiel #21
0
// If the wrapped handler writes no cache headers whatsoever, and a PublicCacheControl
// is used, the Cache-Control header is set with the given maxAge and re-validate value.
// The Last-Modified header is also set to the beginning of (computer) time.  If a
// Pragma header is written is deleted
func TestWrapWithCacheHeaderPublicCacheControlNoCacheHeaders(t *testing.T) {
	mux := http.NewServeMux()
	mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte("hello!"))
	})
	mux.HandleFunc("/a", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Pragma", "no-cache")
		w.Write([]byte("hello!"))
	})

	for _, path := range []string{"/", "/a"} {
		req := &http.Request{URL: &url.URL{Path: path}, Body: ioutil.NopCloser(bytes.NewBuffer(nil))}

		// must-revalidate is set if revalidate is set to true, and not if revalidate is set to false
		for _, revalidate := range []bool{true, false} {
			wrapped := WrapWithCacheHandler(NewCacheControlConfig(10, revalidate), mux)
			require.NotEqual(t, mux, wrapped)
			rw := httptest.NewRecorder()
			wrapped.ServeHTTP(rw, req)

			cacheControl := "public, max-age=10, s-maxage=10"
			if revalidate {
				cacheControl = cacheControl + ", must-revalidate"
			}
			require.Equal(t, cacheControl, rw.HeaderMap.Get("Cache-Control"))

			lastModified, err := time.Parse(time.RFC1123, rw.HeaderMap.Get("Last-Modified"))
			require.NoError(t, err)
			require.True(t, lastModified.Equal(time.Time{}))
			require.Equal(t, "", rw.HeaderMap.Get("Pragma"))
		}
	}
}
Beispiel #22
0
// This modifies the metadata so that the signed part has an extra, extraneous
// field.  This does not prevent it from being unmarshalled as Signed* object,
// but the signature is no longer valid because the hash is different.
func TestSwizzlerInvalidateMetadataSignatures(t *testing.T) {
	f, origMeta := createNewSwizzler(t)

	f.InvalidateMetadataSignatures(data.CanonicalRootRole)

	for role, metaBytes := range origMeta {
		newMeta, err := f.MetadataCache.GetMeta(role, -1)
		require.NoError(t, err)

		if role != data.CanonicalRootRole {
			require.True(t, bytes.Equal(metaBytes, newMeta), "bytes have changed for role %s", role)
		} else {
			require.False(t, bytes.Equal(metaBytes, newMeta))
			// it be JSON unmarshallable into a data.Signed, and it's signed by
			// root, but it is NOT the correct signature because the hash
			// does not match
			origSigned, newSigned := &data.Signed{}, &data.Signed{}
			require.NoError(t, json.Unmarshal(metaBytes, origSigned))
			require.NoError(t, json.Unmarshal(newMeta, newSigned))
			require.Len(t, newSigned.Signatures, len(origSigned.Signatures))
			for i := range origSigned.Signatures {
				require.Equal(t, origSigned.Signatures[i].KeyID, newSigned.Signatures[i].KeyID)
				require.Equal(t, origSigned.Signatures[i].Method, newSigned.Signatures[i].Method)
				require.NotEqual(t, origSigned.Signatures[i].Signature, newSigned.Signatures[i].Signature)
				require.Equal(t, []byte("invalid signature"), newSigned.Signatures[i].Signature)
			}
			require.True(t, bytes.Equal(origSigned.Signed, newSigned.Signed))
		}
	}
}
Beispiel #23
0
// This signs the metadata with the wrong key
func TestSwizzlerSignMetadataWithInvalidKey(t *testing.T) {
	f, origMeta := createNewSwizzler(t)

	f.SignMetadataWithInvalidKey(data.CanonicalTimestampRole)

	for role, metaBytes := range origMeta {
		newMeta, err := f.MetadataCache.GetMeta(role, -1)
		require.NoError(t, err)

		if role != data.CanonicalTimestampRole {
			require.True(t, bytes.Equal(metaBytes, newMeta), "bytes have changed for role %s", role)
		} else {
			require.False(t, bytes.Equal(metaBytes, newMeta))
			// it is JSON unmarshallable as a timestamp, but the signature ID
			// does not match.
			require.NoError(t, json.Unmarshal(newMeta, &data.SignedTimestamp{}))
			origSigned, newSigned := &data.Signed{}, &data.Signed{}
			require.NoError(t, json.Unmarshal(metaBytes, origSigned))
			require.NoError(t, json.Unmarshal(newMeta, newSigned))
			require.Len(t, origSigned.Signatures, 1)
			require.Len(t, newSigned.Signatures, 1)
			require.NotEqual(t, origSigned.Signatures[0].KeyID, newSigned.Signatures[0].KeyID)
		}
	}
}
Beispiel #24
0
func TestInitPaths(t *testing.T) {
	//
	// BITRISE_SOURCE_DIR

	// Unset BITRISE_SOURCE_DIR -> after InitPaths BITRISE_SOURCE_DIR should be CurrentDir
	if os.Getenv(BitriseSourceDirEnvKey) != "" {
		require.Equal(t, nil, os.Unsetenv(BitriseSourceDirEnvKey))
	}
	require.Equal(t, nil, InitPaths())
	require.Equal(t, CurrentDir, os.Getenv(BitriseSourceDirEnvKey))

	// Set BITRISE_SOURCE_DIR -> after InitPaths BITRISE_SOURCE_DIR should keep content
	require.Equal(t, nil, os.Setenv(BitriseSourceDirEnvKey, "$HOME/test"))
	require.Equal(t, nil, InitPaths())
	require.Equal(t, "$HOME/test", os.Getenv(BitriseSourceDirEnvKey))

	//
	// BITRISE_DEPLOY_DIR

	// Unset BITRISE_DEPLOY_DIR -> after InitPaths BITRISE_DEPLOY_DIR should be temp dir
	if os.Getenv(BitriseDeployDirEnvKey) != "" {
		require.Equal(t, nil, os.Unsetenv(BitriseDeployDirEnvKey))
	}
	require.Equal(t, nil, InitPaths())
	require.NotEqual(t, "", os.Getenv(BitriseDeployDirEnvKey))

	// Set BITRISE_DEPLOY_DIR -> after InitPaths BITRISE_DEPLOY_DIR should keep content
	require.Equal(t, nil, os.Setenv(BitriseDeployDirEnvKey, "$HOME/test"))
	require.Equal(t, nil, InitPaths())
	require.Equal(t, "$HOME/test", os.Getenv(BitriseDeployDirEnvKey))
}
Beispiel #25
0
// This adds a single byte of whitespace to the metadata file, so it should be parsed
// and deserialized the same way, but checksums against snapshot/timestamp may fail
func TestSwizzlerAddExtraSpace(t *testing.T) {
	f, origMeta := createNewSwizzler(t)

	f.AddExtraSpace(data.CanonicalTargetsRole)

	snapshot := &data.SignedSnapshot{}
	require.NoError(t, json.Unmarshal(origMeta[data.CanonicalSnapshotRole], snapshot))

	for role, metaBytes := range origMeta {
		newMeta, err := f.MetadataCache.GetMeta(role, -1)
		require.NoError(t, err)

		if role != data.CanonicalTargetsRole {
			require.True(t, bytes.Equal(metaBytes, newMeta), "bytes have changed for role %s", role)
		} else {
			require.False(t, bytes.Equal(metaBytes, newMeta))
			require.True(t, bytes.Equal(metaBytes, newMeta[1:len(metaBytes)+1]))
			require.Equal(t, byte(' '), newMeta[0])
			require.Equal(t, byte(' '), newMeta[len(newMeta)-1])

			// make sure the hash is not the same as the hash in snapshot
			newHash := sha256.Sum256(newMeta)
			require.False(t, bytes.Equal(
				snapshot.Signed.Meta[data.CanonicalTargetsRole].Hashes["sha256"],
				newHash[:]))
			require.NotEqual(t,
				snapshot.Signed.Meta[data.CanonicalTargetsRole].Length,
				len(newMeta))
		}
	}
}
// Workflow
func TestValidate(t *testing.T) {
	workflow := WorkflowModel{
		BeforeRun: []string{"befor1", "befor2", "befor3"},
		AfterRun:  []string{"after1", "after2", "after3"},
	}
	require.Equal(t, nil, workflow.Validate())

	configStr := `
format_version: 1.0.0
default_step_lib_source: "https://github.com/bitrise-io/bitrise-steplib.git"

workflows:
  target:
    envs:
    - ENV_KEY: env_value
      opts:
        title: test_env
    title: Output Test
    steps:
    - script:
        title: Should fail
        inputs:
        - content: echo "Hello"
          BAD_KEY: value
`

	config := BitriseDataModel{}
	require.Equal(t, nil, yaml.Unmarshal([]byte(configStr), &config))
	require.Equal(t, nil, config.Normalize())
	require.NotEqual(t, nil, config.Validate())
	require.Equal(t, true, strings.Contains(config.Validate().Error(), "Invalid env: more than 2 fields:"))
}
Beispiel #27
0
func TestReplaceFile(t *testing.T) {
	dir, err := ioutil.TempDir("", "replace_file")
	require.NoError(t, err, "creating temp dir failed")

	origFilename := filepath.Join(dir, "testfile")

	of, err := os.Create(origFilename)
	require.NoError(t, err, "creating file failed")

	nf, err := openReplace(origFilename)
	require.NoError(t, err, "opening replacement file failed")

	_, err = nf.Write([]byte("test"))
	require.NoError(t, err, "writing replace file failed")

	require.NotEqual(t, nf.Name(), of.Name(), "replacement file must have different name while editing")
	require.NoError(t, nf.Close(), "closing replacement file failed")
	require.NoError(t, of.Close(), "closing original file failed")

	ofr, err := os.Open(origFilename)
	require.NoError(t, err, "opening original file failed")
	defer ofr.Close()

	res, err := ioutil.ReadAll(ofr)
	require.NoError(t, err, "reading original file failed")
	require.Equal(t, "test", string(res), "unexpected file contents")
}
Beispiel #28
0
// Test the case where all short ids are taken, but then some peers go
// away, so the local peer reassigns
func TestDeferredShortIDReassignment(t *testing.T) {
	rng := rand.New(rand.NewSource(time.Now().UnixNano()))
	_, us := newNode(PeerName(1 << peerShortIDBits))

	// Connect us to other peers occupying all short ids
	others := make([]*Peers, 1<<peerShortIDBits)
	var pending peersPendingNotifications
	for i := range others {
		_, others[i] = newNode(PeerName(i))
		others[i].setLocalShortID(PeerShortID(i), &pending)
		us.AddTestConnection(others[i].ourself.Peer)
	}

	// Check that, as expected, the local peer does not own its
	// short id
	require.NotEqual(t, us.ourself.Peer,
		us.byShortID[us.ourself.ShortID].peer)

	// Disconnect one peer, and we should now be able to claim its
	// short id
	other := others[rng.Intn(1<<peerShortIDBits)]
	us.DeleteTestConnection(other.ourself.Peer)
	us.GarbageCollect()

	require.Equal(t, us.ourself.Peer, us.byShortID[us.ourself.ShortID].peer)
}
Beispiel #29
0
// This changes the root key
func TestSwizzlerChangeRootKey(t *testing.T) {
	f, origMeta := createNewSwizzler(t)

	err := f.ChangeRootKey()
	require.NoError(t, err)

	// we want to test these in a specific order
	roles := []string{data.CanonicalRootRole, data.CanonicalTargetsRole, data.CanonicalSnapshotRole,
		data.CanonicalTimestampRole, "targets/a", "targets/a/b"}

	for _, role := range roles {
		origMeta := origMeta[role]
		newMeta, err := f.MetadataCache.GetMeta(role, store.NoSizeLimit)
		require.NoError(t, err)

		// the threshold for base roles is set in root
		switch role {
		case data.CanonicalRootRole:
			require.False(t, bytes.Equal(origMeta, newMeta))
			origRoot, newRoot := &data.SignedRoot{}, &data.SignedRoot{}
			require.NoError(t, json.Unmarshal(origMeta, origRoot))
			require.NoError(t, json.Unmarshal(newMeta, newRoot))

			require.NotEqual(t, len(origRoot.Signed.Keys), len(newRoot.Signed.Keys))

			for r, origRole := range origRoot.Signed.Roles {
				newRole := newRoot.Signed.Roles[r]
				require.Len(t, origRole.KeyIDs, 1)
				require.Len(t, newRole.KeyIDs, 1)
				if r == data.CanonicalRootRole {
					require.NotEqual(t, origRole.KeyIDs[0], newRole.KeyIDs[0])
				} else {
					require.Equal(t, origRole.KeyIDs[0], newRole.KeyIDs[0])
				}
			}

			rootRole, err := newRoot.BuildBaseRole(data.CanonicalRootRole)
			require.NoError(t, err)
			signedThing, err := newRoot.ToSigned()
			require.NoError(t, err)
			require.NoError(t, signed.VerifySignatures(signedThing, rootRole))
			require.NoError(t, signed.VerifyVersion(&(newRoot.Signed.SignedCommon), 1))
		default:
			require.True(t, bytes.Equal(origMeta, newMeta), "bytes have changed for role %s", role)
		}
	}
}
Beispiel #30
0
// Check that we can get the "current" specified role but it is different from the provided TUF file because
// the most valid walk from timestamp --> snapshot --> role gets a different
func ConsistentTSAndSnapGetDifferentCurrentTest(t *testing.T, s *TUFMetaStorage, rec TUFFile) {
	_, byt, err := s.GetCurrent(rec.Gun, rec.Role)
	require.NotEqual(t, rec.Data, byt)
	require.NoError(t, err)
	_, byt, err = s.MetaStore.GetCurrent(rec.Gun, rec.Role)
	require.Equal(t, rec.Data, byt)
	require.NoError(t, err)
}