1package dns
2
3import (
4	"testing"
5)
6
7// This tests everything valid about SVCB but parsing.
8// Parsing tests belong to parse_test.go.
9func TestSVCB(t *testing.T) {
10	svcbs := []struct {
11		key  string
12		data string
13	}{
14		{`mandatory`, `alpn,key65000`},
15		{`alpn`, `h2,h2c`},
16		{`port`, `499`},
17		{`ipv4hint`, `3.4.3.2,1.1.1.1`},
18		{`no-default-alpn`, ``},
19		{`ipv6hint`, `1::4:4:4:4,1::3:3:3:3`},
20		{`echconfig`, `YUdWc2JHOD0=`},
21		{`key65000`, `4\ 3`},
22		{`key65001`, `\"\ `},
23		{`key65002`, ``},
24		{`key65003`, `=\"\"`},
25		{`key65004`, `\254\ \ \030\000`},
26	}
27
28	for _, o := range svcbs {
29		keyCode := svcbStringToKey(o.key)
30		kv := makeSVCBKeyValue(keyCode)
31		if kv == nil {
32			t.Error("failed to parse svc key: ", o.key)
33			continue
34		}
35		if kv.Key() != keyCode {
36			t.Error("key constant is not in sync: ", keyCode)
37			continue
38		}
39		err := kv.parse(o.data)
40		if err != nil {
41			t.Error("failed to parse svc pair: ", o.key)
42			continue
43		}
44		b, err := kv.pack()
45		if err != nil {
46			t.Error("failed to pack value of svc pair: ", o.key, err)
47			continue
48		}
49		if len(b) != int(kv.len()) {
50			t.Errorf("expected packed svc value %s to be of length %d but got %d", o.key, int(kv.len()), len(b))
51		}
52		err = kv.unpack(b)
53		if err != nil {
54			t.Error("failed to unpack value of svc pair: ", o.key, err)
55			continue
56		}
57		if str := kv.String(); str != o.data {
58			t.Errorf("`%s' should be equal to\n`%s', but is     `%s'", o.key, o.data, str)
59		}
60	}
61}
62
63func TestDecodeBadSVCB(t *testing.T) {
64	svcbs := []struct {
65		key  SVCBKey
66		data []byte
67	}{
68		{
69			key:  SVCB_ALPN,
70			data: []byte{3, 0, 0}, // There aren't three octets after 3
71		},
72		{
73			key:  SVCB_NO_DEFAULT_ALPN,
74			data: []byte{0},
75		},
76		{
77			key:  SVCB_PORT,
78			data: []byte{},
79		},
80		{
81			key:  SVCB_IPV4HINT,
82			data: []byte{0, 0, 0},
83		},
84		{
85			key:  SVCB_IPV6HINT,
86			data: []byte{0, 0, 0},
87		},
88	}
89	for _, o := range svcbs {
90		err := makeSVCBKeyValue(SVCBKey(o.key)).unpack(o.data)
91		if err == nil {
92			t.Error("accepted invalid svc value with key ", SVCBKey(o.key).String())
93		}
94	}
95}
96
97func TestCompareSVCB(t *testing.T) {
98	val1 := []SVCBKeyValue{
99		&SVCBPort{
100			Port: 117,
101		},
102		&SVCBAlpn{
103			Alpn: []string{"h2", "h3"},
104		},
105	}
106	val2 := []SVCBKeyValue{
107		&SVCBAlpn{
108			Alpn: []string{"h2", "h3"},
109		},
110		&SVCBPort{
111			Port: 117,
112		},
113	}
114	if !areSVCBPairArraysEqual(val1, val2) {
115		t.Error("svcb pairs were compared without sorting")
116	}
117	if val1[0].Key() != SVCB_PORT || val2[0].Key() != SVCB_ALPN {
118		t.Error("original svcb pairs were reordered during comparison")
119	}
120}
121