~samwhited/xmpp

ref: 19734c657a478b3f4d0657eaea3c4476924a3f7a xmpp/session_test.go -rw-r--r-- 8.6 KiB
19734c65Sam Whited all: add new API to make reading tokens safer 1 year, 10 months ago
                                                                                
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
64
65
66
67
68
69
70
71
72
73
74
75
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
245
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
// Copyright 2017 The Mellium Contributors.
// Use of this source code is governed by the BSD 2-clause
// license that can be found in the LICENSE file.

package xmpp_test

import (
	"bytes"
	"context"
	"encoding/xml"
	"errors"
	"fmt"
	"io"
	"math"
	"strconv"
	"strings"
	"testing"

	"mellium.im/xmlstream"
	"mellium.im/xmpp"
	"mellium.im/xmpp/internal/xmpptest"
	"mellium.im/xmpp/jid"
	"mellium.im/xmpp/stanza"
	"mellium.im/xmpp/stream"
)

func TestClosedInputStream(t *testing.T) {
	for i := 0; i <= math.MaxUint8; i++ {
		t.Run(fmt.Sprintf("%d", i), func(t *testing.T) {
			mask := xmpp.SessionState(i)
			buf := new(bytes.Buffer)
			s := xmpptest.NewSession(mask, buf)
			r := s.TokenReader()
			defer r.Close()

			_, err := r.Token()
			switch {
			case mask&xmpp.InputStreamClosed == xmpp.InputStreamClosed && err != xmpp.ErrInputStreamClosed:
				t.Errorf("Unexpected error: want=`%v', got=`%v'", xmpp.ErrInputStreamClosed, err)
			case mask&xmpp.InputStreamClosed == 0 && err != io.EOF:
				t.Errorf("Unexpected error: `%v'", err)
			}
		})
	}
}

func TestClosedOutputStream(t *testing.T) {
	for i := 0; i <= math.MaxUint8; i++ {
		t.Run(fmt.Sprintf("%d", i), func(t *testing.T) {
			mask := xmpp.SessionState(i)
			buf := new(bytes.Buffer)
			s := xmpptest.NewSession(mask, buf)
			w := s.TokenWriter()
			defer w.Close()

			switch err := w.EncodeToken(xml.CharData("chartoken")); {
			case mask&xmpp.OutputStreamClosed == xmpp.OutputStreamClosed && err != xmpp.ErrOutputStreamClosed:
				t.Errorf("Unexpected error: want=`%v', got=`%v'", xmpp.ErrOutputStreamClosed, err)
			case mask&xmpp.OutputStreamClosed == 0 && err != nil:
				t.Errorf("Unexpected error: `%v'", err)
			}
			switch err := s.Flush(); {
			case mask&xmpp.OutputStreamClosed == xmpp.OutputStreamClosed && err != xmpp.ErrOutputStreamClosed:
				t.Errorf("Unexpected error flushing: want=`%v', got=`%v'", xmpp.ErrOutputStreamClosed, err)
			case mask&xmpp.OutputStreamClosed == 0 && err != nil:
				t.Errorf("Unexpected error: `%v'", err)
			}
		})
	}
}

func TestNilNegotiatorPanics(t *testing.T) {
	defer func() {
		if r := recover(); r == nil {
			t.Error("Expected panic, did not get one")
		}
	}()
	xmpp.NegotiateSession(context.Background(), jid.JID{}, jid.JID{}, nil, false, nil)
}

var errTestNegotiate = errors.New("a test error")

func errNegotiator(ctx context.Context, session *xmpp.Session, data interface{}) (mask xmpp.SessionState, rw io.ReadWriter, cache interface{}, err error) {
	err = errTestNegotiate
	return
}

type negotiateTestCase struct {
	negotiator xmpp.Negotiator
	in         string
	out        string
	location   jid.JID
	origin     jid.JID
	err        error
}

var negotiateTests = [...]negotiateTestCase{
	0: {negotiator: errNegotiator, err: errTestNegotiate},
	1: {
		negotiator: xmpp.NewNegotiator(xmpp.StreamConfig{
			Features: []xmpp.StreamFeature{xmpp.StartTLS(true, nil)},
		}),
		in:  `<stream:stream id='316732270768047465' version='1.0' xml:lang='en' xmlns:stream='http://etherx.jabber.org/streams' xmlns='jabber:client'><stream:features><other/></stream:features>`,
		out: `<?xml version="1.0" encoding="UTF-8"?><stream:stream to='' from='' version='1.0' xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams'><starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'/>`,
		err: errors.New("XML syntax error on line 1: unexpected EOF"),
	},
	2: {
		negotiator: xmpp.NewNegotiator(xmpp.StreamConfig{}),
		in:         `<stream:stream id='316732270768047465' version='1.0' xml:lang='en' xmlns:stream='http://etherx.jabber.org/streams' xmlns='jabber:client'><stream:features><other/></stream:features>`,
		out:        `<?xml version="1.0" encoding="UTF-8"?><stream:stream to='' from='' version='1.0' xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams'>`,
		err:        errors.New("xmpp: features advertised out of order"),
	},
}

func TestNegotiator(t *testing.T) {
	for i, tc := range negotiateTests {
		t.Run(strconv.Itoa(i), func(t *testing.T) {
			buf := &bytes.Buffer{}
			rw := struct {
				io.Reader
				io.Writer
			}{
				Reader: strings.NewReader(tc.in),
				Writer: buf,
			}
			_, err := xmpp.NegotiateSession(context.Background(), tc.location, tc.origin, rw, false, tc.negotiator)
			if ((err == nil || tc.err == nil) && (err != nil || tc.err != nil)) || err.Error() != tc.err.Error() {
				t.Errorf("Unexpected error: want=%q, got=%q", tc.err, err)
			}
			if out := buf.String(); out != tc.out {
				t.Errorf("Unexpected output:\nwant=%q,\n got=%q", tc.out, out)
			}
		})
	}
}

const invalidIQ = `<iq type="error" id="1234"><error type="cancel"><service-unavailable xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"></service-unavailable></error></iq>`

var serveTests = [...]struct {
	handler xmpp.Handler
	out     string
	in      string
	err     error
}{
	0: {
		in:  `<test></test>`,
		out: `</stream:stream>`,
		err: io.EOF,
	},
	1: {
		in:  `a`,
		out: `</stream:stream>`,
		err: stream.BadFormat,
	},
	2: {
		in:  `<iq type="get" id="1234"><unknownpayload xmlns="unknown"/></iq>`,
		out: invalidIQ + `</stream:stream>`,
		err: io.EOF,
	},
	3: {
		handler: xmpp.HandlerFunc(func(s *xmpp.Session, start *xml.StartElement) error {
			w := s.TokenWriter()
			defer w.Close()
			_, err := xmlstream.Copy(w, stanza.WrapIQ(stanza.IQ{
				ID:   "1234",
				Type: stanza.ResultIQ,
			}, nil))
			return err
		}),
		in:  `<iq type="get" id="1234"><unknownpayload xmlns="unknown"/></iq>`,
		out: `<iq type="result" id="1234"></iq></stream:stream>`,
		err: io.EOF,
	},
	4: {
		handler: xmpp.HandlerFunc(func(s *xmpp.Session, start *xml.StartElement) error {
			w := s.TokenWriter()
			defer w.Close()
			_, err := xmlstream.Copy(w, stanza.WrapIQ(stanza.IQ{
				ID:   "wrongid",
				Type: stanza.ResultIQ,
			}, nil))
			return err
		}),
		in:  `<iq type="get" id="1234"><unknownpayload xmlns="unknown"/></iq>`,
		out: `<iq type="result" id="wrongid"></iq>` + invalidIQ + `</stream:stream>`,
		err: io.EOF,
	},
	5: {
		handler: xmpp.HandlerFunc(func(s *xmpp.Session, start *xml.StartElement) error {
			w := s.TokenWriter()
			defer w.Close()
			_, err := xmlstream.Copy(w, stanza.WrapIQ(stanza.IQ{
				ID:   "1234",
				Type: stanza.ErrorIQ,
			}, nil))
			return err
		}),
		in:  `<iq type="get" id="1234"><unknownpayload xmlns="unknown"/></iq>`,
		out: `<iq type="error" id="1234"></iq></stream:stream>`,
		err: io.EOF,
	},
	6: {
		handler: xmpp.HandlerFunc(func(s *xmpp.Session, start *xml.StartElement) error {
			w := s.TokenWriter()
			defer w.Close()
			_, err := xmlstream.Copy(w, stanza.WrapIQ(stanza.IQ{
				ID:   "1234",
				Type: stanza.GetIQ,
			}, nil))
			return err
		}),
		in:  `<iq type="get" id="1234"><unknownpayload xmlns="unknown"/></iq>`,
		out: `<iq type="get" id="1234"></iq>` + invalidIQ + `</stream:stream>`,
		err: io.EOF,
	},
	7: {
		handler: xmpp.HandlerFunc(func(_ *xmpp.Session, start *xml.StartElement) error {
			for _, attr := range start.Attr {
				if attr.Name.Local == "from" && attr.Value != "" {
					panic("expected attr to be normalized")
				}
			}
			return nil
		}),
		in:  `<iq from="test@example.net"></iq>`,
		out: `</stream:stream>`,
		err: io.EOF,
	},
	8: {
		handler: xmpp.HandlerFunc(func(_ *xmpp.Session, start *xml.StartElement) error {
			for _, attr := range start.Attr {
				if attr.Name.Local == "from" && attr.Value == "" {
					panic("expected attr not to be normalized")
				}
			}
			return nil
		}),
		in:  `<iq from="test@example.net/test"></iq>`,
		out: `</stream:stream>`,
		err: io.EOF,
	},
	9: {
		handler: xmpp.HandlerFunc(func(_ *xmpp.Session, start *xml.StartElement) error {
			for _, attr := range start.Attr {
				if attr.Name.Local == "from" && attr.Value == "" {
					panic("expected attr not to be normalized")
				}
			}
			return nil
		}),
		in:  `<iq from="test2@example.net"></iq>`,
		out: `</stream:stream>`,
		err: io.EOF,
	},
	10: {
		handler: xmpp.HandlerFunc(func(_ *xmpp.Session, start *xml.StartElement) error {
			for _, attr := range start.Attr {
				if attr.Name.Local == "from" && attr.Value == "" {
					panic("expected attr not to be normalized")
				}
			}
			return nil
		}),
		in:  `<iq from="test@example.com"></iq>`,
		out: `</stream:stream>`,
		err: io.EOF,
	},
}

func TestServe(t *testing.T) {
	for i, tc := range serveTests {
		t.Run(strconv.Itoa(i), func(t *testing.T) {
			out := &bytes.Buffer{}
			in := strings.NewReader(tc.in)
			s := xmpptest.NewSession(0, struct {
				io.Reader
				io.Writer
			}{
				Reader: in,
				Writer: out,
			})

			err := s.Serve(tc.handler)
			if err != tc.err {
				t.Errorf("Unexpected error: want=%q, got=%q", tc.err, err)
			}
			if s := out.String(); s != tc.out {
				t.Errorf("Unexpected output:\nwant=%q,\n got=%q", tc.out, s)
			}
			if l := in.Len(); l != 0 {
				t.Errorf("Did not finish read, %d bytes left", l)
			}
		})
	}
}