envelope_test.go 7.76 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
package record_test

import (
	"bytes"
	"errors"
	"testing"

	crypto "github.com/libp2p/go-libp2p-core/crypto"
	. "github.com/libp2p/go-libp2p-core/record"
	pb "github.com/libp2p/go-libp2p-core/record/pb"
	"github.com/libp2p/go-libp2p-core/test"

	"github.com/gogo/protobuf/proto"
)

type simpleRecord struct {
	testDomain *string
	testCodec  []byte
	message    string
}

func (r *simpleRecord) Domain() string {
	if r.testDomain != nil {
		return *r.testDomain
	}
	return "libp2p-testing"
}

func (r *simpleRecord) Codec() []byte {
	if r.testCodec != nil {
		return r.testCodec
	}
	return []byte("/libp2p/testdata")
}

func (r *simpleRecord) MarshalRecord() ([]byte, error) {
	return []byte(r.message), nil
}

func (r *simpleRecord) UnmarshalRecord(buf []byte) error {
	r.message = string(buf)
	return nil
}

// Make an envelope, verify & open it, marshal & unmarshal it
func TestEnvelopeHappyPath(t *testing.T) {
	var (
		rec            = &simpleRecord{message: "hello world!"}
		priv, pub, err = test.RandTestKeyPair(crypto.Ed25519, 256)
	)

	test.AssertNilError(t, err)

	payload, err := rec.MarshalRecord()
	test.AssertNilError(t, err)

	envelope, err := Seal(rec, priv)
	test.AssertNilError(t, err)

	if !envelope.PublicKey.Equals(pub) {
		t.Error("envelope has unexpected public key")
	}

Marten Seemann's avatar
Marten Seemann committed
64
	if !bytes.Equal(rec.Codec(), envelope.PayloadType) {
65 66 67 68 69 70 71 72 73 74
		t.Error("PayloadType does not match record Codec")
	}

	serialized, err := envelope.Marshal()
	test.AssertNilError(t, err)

	RegisterType(&simpleRecord{})
	deserialized, rec2, err := ConsumeEnvelope(serialized, rec.Domain())
	test.AssertNilError(t, err)

Marten Seemann's avatar
Marten Seemann committed
75
	if !bytes.Equal(deserialized.RawPayload, payload) {
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244
		t.Error("payload of envelope does not match input")
	}

	if !envelope.Equal(deserialized) {
		t.Error("round-trip serde results in unequal envelope structures")
	}

	typedRec, ok := rec2.(*simpleRecord)
	if !ok {
		t.Error("expected ConsumeEnvelope to return record with type registered for payloadType")
	}
	if typedRec.message != "hello world!" {
		t.Error("unexpected alteration of record")
	}
}

func TestConsumeTypedEnvelope(t *testing.T) {
	var (
		rec          = simpleRecord{message: "hello world!"}
		priv, _, err = test.RandTestKeyPair(crypto.Ed25519, 256)
	)

	envelope, err := Seal(&rec, priv)
	test.AssertNilError(t, err)

	envelopeBytes, err := envelope.Marshal()
	test.AssertNilError(t, err)

	rec2 := &simpleRecord{}
	_, err = ConsumeTypedEnvelope(envelopeBytes, rec2)
	test.AssertNilError(t, err)

	if rec2.message != "hello world!" {
		t.Error("unexpected alteration of record")
	}
}

func TestMakeEnvelopeFailsWithEmptyDomain(t *testing.T) {
	var (
		rec          = simpleRecord{message: "hello world!"}
		domain       = ""
		priv, _, err = test.RandTestKeyPair(crypto.Ed25519, 256)
	)

	if err != nil {
		t.Fatal(err)
	}

	// override domain with empty string
	rec.testDomain = &domain

	_, err = Seal(&rec, priv)
	test.ExpectError(t, err, "making an envelope with an empty domain should fail")
}

func TestMakeEnvelopeFailsWithEmptyPayloadType(t *testing.T) {
	var (
		rec          = simpleRecord{message: "hello world!"}
		priv, _, err = test.RandTestKeyPair(crypto.Ed25519, 256)
	)

	if err != nil {
		t.Fatal(err)
	}

	// override payload with empty slice
	rec.testCodec = []byte{}

	_, err = Seal(&rec, priv)
	test.ExpectError(t, err, "making an envelope with an empty payloadType should fail")
}

type failingRecord struct {
	allowMarshal   bool
	allowUnmarshal bool
}

func (r failingRecord) Domain() string {
	return "testing"
}

func (r failingRecord) Codec() []byte {
	return []byte("doesn't matter")
}

func (r failingRecord) MarshalRecord() ([]byte, error) {
	if r.allowMarshal {
		return []byte{}, nil
	}
	return nil, errors.New("marshal failed")
}
func (r failingRecord) UnmarshalRecord(data []byte) error {
	if r.allowUnmarshal {
		return nil
	}
	return errors.New("unmarshal failed")
}

func TestSealFailsIfRecordMarshalFails(t *testing.T) {
	var (
		priv, _, err = test.RandTestKeyPair(crypto.Ed25519, 256)
	)

	if err != nil {
		t.Fatal(err)
	}
	rec := failingRecord{}
	_, err = Seal(rec, priv)
	test.ExpectError(t, err, "Seal should fail if Record fails to marshal")
}

func TestConsumeEnvelopeFailsIfEnvelopeUnmarshalFails(t *testing.T) {
	_, _, err := ConsumeEnvelope([]byte("not an Envelope protobuf"), "doesn't-matter")
	test.ExpectError(t, err, "ConsumeEnvelope should fail if Envelope fails to unmarshal")
}

func TestConsumeEnvelopeFailsIfRecordUnmarshalFails(t *testing.T) {
	var (
		priv, _, err = test.RandTestKeyPair(crypto.Ed25519, 256)
	)

	if err != nil {
		t.Fatal(err)
	}

	RegisterType(failingRecord{})
	rec := failingRecord{allowMarshal: true}
	env, err := Seal(rec, priv)
	test.AssertNilError(t, err)
	envBytes, err := env.Marshal()
	test.AssertNilError(t, err)

	_, _, err = ConsumeEnvelope(envBytes, rec.Domain())
	test.ExpectError(t, err, "ConsumeEnvelope should fail if Record fails to unmarshal")
}

func TestConsumeTypedEnvelopeFailsIfRecordUnmarshalFails(t *testing.T) {
	var (
		priv, _, err = test.RandTestKeyPair(crypto.Ed25519, 256)
	)

	if err != nil {
		t.Fatal(err)
	}

	RegisterType(failingRecord{})
	rec := failingRecord{allowMarshal: true}
	env, err := Seal(rec, priv)
	test.AssertNilError(t, err)
	envBytes, err := env.Marshal()
	test.AssertNilError(t, err)

	rec2 := failingRecord{}
	_, err = ConsumeTypedEnvelope(envBytes, rec2)
	test.ExpectError(t, err, "ConsumeTypedEnvelope should fail if Record fails to unmarshal")
}

func TestEnvelopeValidateFailsForDifferentDomain(t *testing.T) {
	var (
		rec          = &simpleRecord{message: "hello world"}
		priv, _, err = test.RandTestKeyPair(crypto.Ed25519, 256)
	)

	test.AssertNilError(t, err)

	envelope, err := Seal(rec, priv)
	test.AssertNilError(t, err)

	serialized, err := envelope.Marshal()
Marten Seemann's avatar
Marten Seemann committed
245
	test.AssertNilError(t, err)
246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314

	// try to open our modified envelope
	_, _, err = ConsumeEnvelope(serialized, "wrong-domain")
	test.ExpectError(t, err, "should not be able to open envelope with incorrect domain")
}

func TestEnvelopeValidateFailsIfPayloadTypeIsAltered(t *testing.T) {
	var (
		rec          = &simpleRecord{message: "hello world!"}
		domain       = "libp2p-testing"
		priv, _, err = test.RandTestKeyPair(crypto.Ed25519, 256)
	)

	test.AssertNilError(t, err)

	envelope, err := Seal(rec, priv)
	test.AssertNilError(t, err)

	serialized := alterMessageAndMarshal(t, envelope, func(msg *pb.Envelope) {
		msg.PayloadType = []byte("foo")
	})

	// try to open our modified envelope
	_, _, err = ConsumeEnvelope(serialized, domain)
	test.ExpectError(t, err, "should not be able to open envelope with modified PayloadType")
}

func TestEnvelopeValidateFailsIfContentsAreAltered(t *testing.T) {
	var (
		rec          = &simpleRecord{message: "hello world!"}
		domain       = "libp2p-testing"
		priv, _, err = test.RandTestKeyPair(crypto.Ed25519, 256)
	)

	test.AssertNilError(t, err)

	envelope, err := Seal(rec, priv)
	test.AssertNilError(t, err)

	serialized := alterMessageAndMarshal(t, envelope, func(msg *pb.Envelope) {
		msg.Payload = []byte("totally legit, trust me")
	})

	// try to open our modified envelope
	_, _, err = ConsumeEnvelope(serialized, domain)
	test.ExpectError(t, err, "should not be able to open envelope with modified payload")
}

// Since we're outside of the crypto package (to avoid import cycles with test package),
// we can't alter the fields in a Envelope directly. This helper marshals
// the envelope to a protobuf and calls the alterMsg function, which should
// alter the protobuf message.
// Returns the serialized altered protobuf message.
func alterMessageAndMarshal(t *testing.T, envelope *Envelope, alterMsg func(*pb.Envelope)) []byte {
	t.Helper()

	serialized, err := envelope.Marshal()
	test.AssertNilError(t, err)

	msg := pb.Envelope{}
	err = proto.Unmarshal(serialized, &msg)
	test.AssertNilError(t, err)

	alterMsg(&msg)
	serialized, err = msg.Marshal()
	test.AssertNilError(t, err)

	return serialized
}