Debian Codegraph @

server/api/handlers_test.go

raw
1 /*
2 Copyright 2013-2014 Canonical Ltd.
3
4 This program is free software: you can redistribute it and/or modify it
5 under the terms of the GNU General Public License version 3, as published
6 by the Free Software Foundation.
7
8 This program is distributed in the hope that it will be useful, but
9 WITHOUT ANY WARRANTY; without even the implied warranties of
10 MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
11 PURPOSE. See the GNU General Public License for more details.
12
13 You should have received a copy of the GNU General Public License along
14 with this program. If not, see <http://www.gnu.org/licenses/>.
15 */
16
17 package api
18
19 import (
20 "bytes"
21 "encoding/base64"
22 "encoding/json"
23 "errors"
24 "fmt"
25 "io/ioutil"
26 "net/http"
27 "net/http/httptest"
28 "strings"
29 "testing"
30 "time"
31
32 . "gopkg.in/check.v1"
33
34 "gitlab.com/ubports/development/core/lomiri-push-service/protocol"
35 "gitlab.com/ubports/development/core/lomiri-push-service/server/store"
36 help "gitlab.com/ubports/development/core/lomiri-push-service/testing"
37 )
38
39 func TestHandlers(t *testing.T) { TestingT(t) }
40
41 type handlersSuite struct {
42 messageEndpoint string
43 json string
44 client *http.Client
45 c *C
46 testlog *help.TestLogger
47 }
48
49 var _ = Suite(&handlersSuite{})
50
51 func (s *handlersSuite) SetUpTest(c *C) {
52 s.client = &http.Client{}
53 s.testlog = help.NewTestLogger(c, "error")
54 }
55
56 func (s *handlersSuite) TestAPIError(c *C) {
57 var apiErr error = &APIError{400, invalidRequest, "Message", nil}
58 c.Check(apiErr.Error(), Equals, "api invalid-request: Message")
59 wire, err := json.Marshal(apiErr)
60 c.Assert(err, IsNil)
61 c.Check(string(wire), Equals, `{"error":"invalid-request","message":"Message"}`)
62 }
63
64 func (s *handlersSuite) TestAPIErrorExtra(c *C) {
65 apiErr1 := &APIError{400, invalidRequest, "Message", nil}
66 payload := json.RawMessage(`{"x":1}`)
67 apiErr := apiErrorWithExtra(apiErr1, &payload)
68 c.Check(apiErr1.Extra, IsNil)
69 c.Check(apiErr.Error(), Equals, "api invalid-request: Message")
70 wire, err := json.Marshal(apiErr)
71 c.Assert(err, IsNil)
72 c.Check(string(wire), Equals, `{"error":"invalid-request","message":"Message","extra":{"x":1}}`)
73 }
74
75 func (s *handlersSuite) TestReadBodyReadError(c *C) {
76 r := bytes.NewReader([]byte{}) // eof too early
77 req, err := http.NewRequest("POST", "", r)
78 c.Assert(err, IsNil)
79 req.Header.Set("Content-Type", "application/json")
80 req.ContentLength = 1000
81 _, err = ReadBody(req, 2000)
82 c.Check(err, Equals, ErrCouldNotReadBody)
83 }
84
85 func (s *handlersSuite) TestReadBodyTooBig(c *C) {
86 r := bytes.NewReader([]byte{}) // not read
87 req, err := http.NewRequest("POST", "", r)
88 c.Assert(err, IsNil)
89 req.Header.Set("Content-Type", "application/json")
90 req.ContentLength = 3000
91 _, err = ReadBody(req, 2000)
92 c.Check(err, Equals, ErrRequestBodyTooLarge)
93
94 req.ContentLength = MaxRequestBodyBytes + 1
95 _, err = ReadBody(req, MaxRequestBodyBytes)
96 c.Check(err, Equals, ErrRequestBodyTooLarge)
97 }
98
99 type testStoreAccess func(w http.ResponseWriter, request *http.Request) (store.PendingStore, error)
100
101 func (tsa testStoreAccess) StoreForRequest(w http.ResponseWriter, request *http.Request) (store.PendingStore, error) {
102 return tsa(w, request)
103 }
104
105 func (tsa testStoreAccess) GetMaxNotificationsPerApplication() int {
106 return 4
107 }
108
109 func (s *handlersSuite) TestGetStore(c *C) {
110 ctx := &context{storage: testStoreAccess(func(w http.ResponseWriter, r *http.Request) (store.PendingStore, error) {
111 return nil, ErrStoreUnavailable
112 })}
113 sto, apiErr := ctx.getStore(nil, nil)
114 c.Check(sto, IsNil)
115 c.Check(apiErr, Equals, ErrStoreUnavailable)
116
117 ctx = &context{storage: testStoreAccess(func(w http.ResponseWriter, r *http.Request) (store.PendingStore, error) {
118 return nil, errors.New("something else")
119 }), logger: s.testlog}
120 sto, apiErr = ctx.getStore(nil, nil)
121 c.Check(sto, IsNil)
122 c.Check(apiErr, Equals, ErrUnknown)
123 c.Check(s.testlog.Captured(), Equals, "ERROR failed to get store: something else\n")
124 }
125
126 var future = time.Now().Add(4 * time.Hour).Format(time.RFC3339)
127
128 func (s *handlersSuite) TestCheckCastBroadcastAndCommon(c *C) {
129 payload := json.RawMessage(`{"foo":"bar"}`)
130 broadcast := &Broadcast{
131 Channel: "system",
132 ExpireOn: future,
133 Data: payload,
134 }
135 expire, err := checkBroadcast(broadcast)
136 c.Check(err, IsNil)
137 c.Check(expire.Format(time.RFC3339), Equals, future)
138
139 broadcast = &Broadcast{
140 Channel: "system",
141 ExpireOn: future,
142 }
143 _, err = checkBroadcast(broadcast)
144 c.Check(err, Equals, ErrMissingData)
145
146 broadcast = &Broadcast{
147 Channel: "system",
148 ExpireOn: "12:00",
149 Data: payload,
150 }
151 _, err = checkBroadcast(broadcast)
152 c.Check(err, Equals, ErrInvalidExpiration)
153
154 broadcast = &Broadcast{
155 Channel: "system",
156 ExpireOn: time.Now().Add(-10 * time.Hour).Format(time.RFC3339),
157 Data: payload,
158 }
159 _, err = checkBroadcast(broadcast)
160 c.Check(err, Equals, ErrPastExpiration)
161 }
162
163 type checkBrokerSending struct {
164 store store.PendingStore
165 chanId store.InternalChannelId
166 err error
167 top int64
168 notifications []protocol.Notification
169 meta []store.Metadata
170 }
171
172 func (cbsend *checkBrokerSending) Broadcast(chanId store.InternalChannelId) {
173 top, notifications, meta, err := cbsend.store.GetChannelUnfiltered(chanId)
174 cbsend.err = err
175 cbsend.chanId = chanId
176 cbsend.top = top
177 cbsend.notifications = notifications
178 cbsend.meta = meta
179 }
180
181 func (cbsend *checkBrokerSending) Unicast(chanIds ...store.InternalChannelId) {
182 // for now
183 if len(chanIds) != 1 {
184 panic("not expecting many chan ids for now")
185 }
186 cbsend.Broadcast(chanIds[0])
187 }
188
189 func (s *handlersSuite) TestDoBroadcast(c *C) {
190 sto := store.NewInMemoryPendingStore()
191 bsend := &checkBrokerSending{store: sto}
192 ctx := &context{nil, bsend, nil}
193 payload := json.RawMessage(`{"a": 1}`)
194 res, apiErr := doBroadcast(ctx, sto, &Broadcast{
195 Channel: "system",
196 ExpireOn: future,
197 Data: payload,
198 })
199 c.Assert(apiErr, IsNil)
200 c.Assert(res, IsNil)
201 c.Check(bsend.err, IsNil)
202 c.Check(bsend.chanId, Equals, store.SystemInternalChannelId)
203 c.Check(bsend.top, Equals, int64(1))
204 c.Check(bsend.notifications, DeepEquals, help.Ns(payload))
205 }
206
207 func (s *handlersSuite) TestDoBroadcastUnknownChannel(c *C) {
208 sto := store.NewInMemoryPendingStore()
209 _, apiErr := doBroadcast(nil, sto, &Broadcast{
210 Channel: "unknown",
211 ExpireOn: future,
212 Data: json.RawMessage(`{"a": 1}`),
213 })
214 c.Check(apiErr, Equals, ErrUnknownChannel)
215 }
216
217 type interceptInMemoryPendingStore struct {
218 *store.InMemoryPendingStore
219 intercept func(meth string, err error) error
220 }
221
222 func (isto *interceptInMemoryPendingStore) Register(appId, deviceId string) (string, error) {
223 token, err := isto.InMemoryPendingStore.Register(appId, deviceId)
224 return token, isto.intercept("Register", err)
225 }
226
227 func (isto *interceptInMemoryPendingStore) Unregister(appId, deviceId string) error {
228 err := isto.InMemoryPendingStore.Unregister(appId, deviceId)
229 return isto.intercept("Unregister", err)
230 }
231
232 func (isto *interceptInMemoryPendingStore) GetInternalChannelIdFromToken(token, appId, userId, deviceId string) (store.InternalChannelId, error) {
233 chanId, err := isto.InMemoryPendingStore.GetInternalChannelIdFromToken(token, appId, userId, deviceId)
234 return chanId, isto.intercept("GetInternalChannelIdFromToken", err)
235 }
236
237 func (isto *interceptInMemoryPendingStore) GetInternalChannelId(channel string) (store.InternalChannelId, error) {
238 chanId, err := isto.InMemoryPendingStore.GetInternalChannelId(channel)
239 return chanId, isto.intercept("GetInternalChannelId", err)
240 }
241
242 func (isto *interceptInMemoryPendingStore) AppendToChannel(chanId store.InternalChannelId, payload json.RawMessage, expiration time.Time) error {
243 err := isto.InMemoryPendingStore.AppendToChannel(chanId, payload, expiration)
244 return isto.intercept("AppendToChannel", err)
245 }
246
247 func (isto *interceptInMemoryPendingStore) AppendToUnicastChannel(chanId store.InternalChannelId, appId string, payload json.RawMessage, msgId string, meta store.Metadata) error {
248 err := isto.InMemoryPendingStore.AppendToUnicastChannel(chanId, appId, payload, msgId, meta)
249 return isto.intercept("AppendToUnicastChannel", err)
250 }
251
252 func (isto *interceptInMemoryPendingStore) GetChannelUnfiltered(chanId store.InternalChannelId) (int64, []protocol.Notification, []store.Metadata, error) {
253 top, notifs, meta, err := isto.InMemoryPendingStore.GetChannelUnfiltered(chanId)
254 return top, notifs, meta, isto.intercept("GetChannelUnfiltered", err)
255 }
256
257 func (isto *interceptInMemoryPendingStore) Scrub(chanId store.InternalChannelId, criteria ...string) error {
258 err := isto.InMemoryPendingStore.Scrub(chanId, criteria...)
259 return isto.intercept("Scrub", err)
260 }
261
262 func (s *handlersSuite) TestDoBroadcastUnknownError(c *C) {
263 sto := &interceptInMemoryPendingStore{
264 store.NewInMemoryPendingStore(),
265 func(meth string, err error) error {
266 return errors.New("other")
267 },
268 }
269 _, apiErr := doBroadcast(nil, sto, &Broadcast{
270 Channel: "system",
271 ExpireOn: future,
272 Data: json.RawMessage(`{"a": 1}`),
273 })
274 c.Check(apiErr, Equals, ErrUnknown)
275 }
276
277 func (s *handlersSuite) TestDoBroadcastCouldNotStoreNotification(c *C) {
278 sto := &interceptInMemoryPendingStore{
279 store.NewInMemoryPendingStore(),
280 func(meth string, err error) error {
281 if meth == "AppendToChannel" {
282 return errors.New("fail")
283 }
284 return err
285 },
286 }
287 ctx := &context{logger: s.testlog}
288 _, apiErr := doBroadcast(ctx, sto, &Broadcast{
289 Channel: "system",
290 ExpireOn: future,
291 Data: json.RawMessage(`{"a": 1}`),
292 })
293 c.Check(apiErr, Equals, ErrCouldNotStoreNotification)
294 c.Check(s.testlog.Captured(), Equals, "ERROR could not store notification: fail\n")
295 }
296
297 func (s *handlersSuite) TestCheckUnicast(c *C) {
298 payload := json.RawMessage(`{"foo":"bar"}`)
299 unicast := func() *Unicast {
300 return &Unicast{
301 UserId: "user1",
302 DeviceId: "DEV1",
303 AppId: "app1",
304 ExpireOn: future,
305 Data: payload,
306 }
307 }
308 u := unicast()
309 expire, apiErr := checkUnicast(u)
310 c.Assert(apiErr, IsNil)
311 c.Check(expire.Format(time.RFC3339), Equals, future)
312
313 u = unicast()
314 u.UserId = ""
315 u.DeviceId = ""
316 u.Token = "TOKEN"
317 expire, apiErr = checkUnicast(u)
318 c.Assert(apiErr, IsNil)
319 c.Check(expire.Format(time.RFC3339), Equals, future)
320
321 u = unicast()
322 u.UserId = ""
323 expire, apiErr = checkUnicast(u)
324 c.Check(apiErr, Equals, ErrMissingIdField)
325
326 u = unicast()
327 u.AppId = ""
328 expire, apiErr = checkUnicast(u)
329 c.Check(apiErr, Equals, ErrMissingIdField)
330
331 u = unicast()
332 u.DeviceId = ""
333 expire, apiErr = checkUnicast(u)
334 c.Check(apiErr, Equals, ErrMissingIdField)
335
336 u = unicast()
337 u.Data = json.RawMessage(nil)
338 expire, apiErr = checkUnicast(u)
339 c.Check(apiErr, Equals, ErrMissingData)
340
341 u = unicast()
342 u.Data = json.RawMessage("{" + strings.Repeat(" ", MaxUnicastPayload - 2) + "}")
343 expire, apiErr = checkUnicast(u)
344 c.Check(apiErr, IsNil)
345
346 u = unicast()
347 u.Data = json.RawMessage("{" + strings.Repeat(" ", MaxUnicastPayload - 2 + 1) + "}")
348 expire, apiErr = checkUnicast(u)
349 c.Check(apiErr, Equals, ErrDataTooLarge)
350 }
351
352 func (s *handlersSuite) TestGenerateMsgId(c *C) {
353 msgId := generateMsgId()
354 decoded, err := base64.StdEncoding.DecodeString(msgId)
355 c.Assert(err, IsNil)
356 c.Check(decoded, HasLen, 16)
357 }
358
359 func (s *handlersSuite) TestDoUnicast(c *C) {
360 prevGenMsgId := generateMsgId
361 defer func() {
362 generateMsgId = prevGenMsgId
363 }()
364 generateMsgId = func() string {
365 return "MSG-ID"
366 }
367 sto := store.NewInMemoryPendingStore()
368 bsend := &checkBrokerSending{store: sto}
369 ctx := &context{testStoreAccess(nil), bsend, s.testlog}
370 payload := json.RawMessage(`{"a": 1}`)
371 res, apiErr := doUnicast(ctx, sto, &Unicast{
372 UserId: "user1",
373 DeviceId: "DEV1",
374 AppId: "app1",
375 ExpireOn: future,
376 Data: payload,
377 })
378 c.Assert(apiErr, IsNil)
379 c.Check(res, IsNil)
380 c.Check(bsend.err, IsNil)
381 c.Check(bsend.chanId, Equals, store.UnicastInternalChannelId("user1", "DEV1"))
382 c.Check(bsend.top, Equals, int64(0))
383 c.Check(bsend.notifications, DeepEquals, []protocol.Notification{
384 protocol.Notification{
385 AppId: "app1",
386 MsgId: "MSG-ID",
387 Payload: payload,
388 },
389 })
390 }
391
392 func (s *handlersSuite) TestDoUnicastMissingIdField(c *C) {
393 sto := store.NewInMemoryPendingStore()
394 _, apiErr := doUnicast(nil, sto, &Unicast{
395 ExpireOn: future,
396 Data: json.RawMessage(`{"a": 1}`),
397 })
398 c.Check(apiErr, Equals, ErrMissingIdField)
399 }
400
401 func (s *handlersSuite) TestDoUnicastCouldNotStoreNotification(c *C) {
402 sto := &interceptInMemoryPendingStore{
403 store.NewInMemoryPendingStore(),
404 func(meth string, err error) error {
405 if meth == "AppendToUnicastChannel" {
406 return errors.New("fail")
407 }
408 return err
409 },
410 }
411 ctx := &context{storage: testStoreAccess(nil), logger: s.testlog}
412 _, apiErr := doUnicast(ctx, sto, &Unicast{
413 UserId: "user1",
414 DeviceId: "DEV1",
415 AppId: "app1",
416 ExpireOn: future,
417 Data: json.RawMessage(`{"a": 1}`),
418 })
419 c.Check(apiErr, Equals, ErrCouldNotStoreNotification)
420 c.Check(s.testlog.Captured(), Equals, "ERROR could not store notification: fail\n")
421 }
422
423 func (s *handlersSuite) TestDoUnicastCouldNotPeekAtNotifications(c *C) {
424 sto := &interceptInMemoryPendingStore{
425 store.NewInMemoryPendingStore(),
426 func(meth string, err error) error {
427 if meth == "GetChannelUnfiltered" {
428 return errors.New("fail")
429 }
430 return err
431 },
432 }
433 ctx := &context{storage: testStoreAccess(nil), logger: s.testlog}
434 _, apiErr := doUnicast(ctx, sto, &Unicast{
435 UserId: "user1",
436 DeviceId: "DEV1",
437 AppId: "app1",
438 ExpireOn: future,
439 Data: json.RawMessage(`{"a": 1}`),
440 })
441 c.Check(apiErr, Equals, ErrCouldNotStoreNotification)
442 c.Check(s.testlog.Captured(), Equals, "ERROR could not peek at notifications: fail\n")
443 }
444
445 func (s *handlersSuite) TestDoUnicastTooManyNotifications(c *C) {
446 sto := store.NewInMemoryPendingStore()
447 chanId := store.UnicastInternalChannelId("user1", "DEV1")
448
449 expire := store.Metadata{Expiration: time.Now().Add(4 * time.Hour)}
450 n1 := json.RawMessage(`{"o":1}`)
451 n2 := json.RawMessage(`{"o":2}`)
452 n3 := json.RawMessage(`{"o":3}`)
453 n4 := json.RawMessage(`{"o":4}`)
454 sto.AppendToUnicastChannel(chanId, "app1", n1, "m1", expire)
455 sto.AppendToUnicastChannel(chanId, "app1", n2, "m2", expire)
456 sto.AppendToUnicastChannel(chanId, "app1", n3, "m3", expire)
457 sto.AppendToUnicastChannel(chanId, "app1", n4, "m4", expire)
458
459 ctx := &context{storage: testStoreAccess(nil), logger: s.testlog}
460 _, apiErr := doUnicast(ctx, sto, &Unicast{
461 UserId: "user1",
462 DeviceId: "DEV1",
463 AppId: "app1",
464 ExpireOn: future,
465 Data: json.RawMessage(`{"a": 1}`),
466 })
467 c.Assert(apiErr, NotNil)
468 extra := apiErr.Extra
469 apiErr.Extra = nil
470 c.Check(apiErr, DeepEquals, ErrTooManyPendingNotifications)
471 c.Check(extra, DeepEquals, n4)
472 c.Check(s.testlog.Captured(), Equals, "")
473 }
474
475 func (s *handlersSuite) TestDoUnicastWithScrub(c *C) {
476 prevGenMsgId := generateMsgId
477 defer func() {
478 generateMsgId = prevGenMsgId
479 }()
480 generateMsgId = func() string {
481 return "MSG-ID"
482 }
483 sto := store.NewInMemoryPendingStore()
484 chanId := store.UnicastInternalChannelId("user1", "DEV1")
485 expire := store.Metadata{Expiration: time.Now().Add(4 * time.Hour)}
486 old := store.Metadata{Expiration: time.Now().Add(-1 * time.Hour)}
487 n := json.RawMessage("{}")
488 sto.AppendToUnicastChannel(chanId, "app1", n, "m1", expire)
489 sto.AppendToUnicastChannel(chanId, "app1", n, "m2", old)
490 sto.AppendToUnicastChannel(chanId, "app1", n, "m3", old)
491 sto.AppendToUnicastChannel(chanId, "app1", n, "m4", expire)
492
493 bsend := &checkBrokerSending{store: sto}
494 ctx := &context{testStoreAccess(nil), bsend, s.testlog}
495 payload := json.RawMessage(`{"a": 1}`)
496 res, apiErr := doUnicast(ctx, sto, &Unicast{
497 UserId: "user1",
498 DeviceId: "DEV1",
499 AppId: "app1",
500 ExpireOn: future,
501 Data: payload,
502 })
503 c.Assert(apiErr, IsNil)
504 c.Check(res, IsNil)
505 c.Check(bsend.err, IsNil)
506 c.Check(bsend.chanId, Equals, store.UnicastInternalChannelId("user1", "DEV1"))
507 c.Check(bsend.top, Equals, int64(0))
508 c.Check(bsend.notifications, HasLen, 3)
509 c.Check(bsend.notifications[0].MsgId, Equals, "m1")
510 c.Check(bsend.notifications[1].MsgId, Equals, "m4")
511 c.Check(bsend.notifications[2], DeepEquals, protocol.Notification{
512 AppId: "app1",
513 MsgId: "MSG-ID",
514 Payload: payload,
515 })
516 }
517
518 func (s *handlersSuite) TestDoUnicastWithReplaceTag(c *C) {
519 prevGenMsgId := generateMsgId
520 defer func() {
521 generateMsgId = prevGenMsgId
522 }()
523 m := 0
524 generateMsgId = func() string {
525 m++
526 return fmt.Sprintf("MSG-ID-%d", m)
527 }
528 sto := store.NewInMemoryPendingStore()
529 chanId := store.UnicastInternalChannelId("user1", "DEV1")
530 expire := store.Metadata{Expiration: time.Now().Add(-1 * time.Hour)}
531 n := json.RawMessage("{}")
532 sto.AppendToUnicastChannel(chanId, "app1", n, "m1", expire)
533
534 bsend := &checkBrokerSending{store: sto}
535 ctx := &context{testStoreAccess(nil), bsend, s.testlog}
536 payload := json.RawMessage(`{"a": 1}`)
537 res, apiErr := doUnicast(ctx, sto, &Unicast{
538 UserId: "user1",
539 DeviceId: "DEV1",
540 AppId: "app1",
541 ExpireOn: future,
542 ReplaceTag: "u1",
543 Data: payload,
544 })
545 c.Assert(apiErr, IsNil)
546 c.Check(res, IsNil)
547 c.Check(bsend.err, IsNil)
548 c.Check(bsend.chanId, Equals, store.UnicastInternalChannelId("user1", "DEV1"))
549 c.Check(bsend.top, Equals, int64(0))
550 c.Check(bsend.notifications, HasLen, 1)
551 c.Check(bsend.notifications[0], DeepEquals, protocol.Notification{
552 AppId: "app1",
553 MsgId: "MSG-ID-1",
554 Payload: payload,
555 })
556 futureTime, err := time.Parse(time.RFC3339, future)
557 c.Assert(err, IsNil)
558 c.Check(bsend.meta[0], DeepEquals, store.Metadata{
559 Expiration: futureTime,
560 ReplaceTag: "u1",
561 })
562
563 // replace
564 payload2 := json.RawMessage(`{"a": 2}`)
565 res, apiErr = doUnicast(ctx, sto, &Unicast{
566 UserId: "user1",
567 DeviceId: "DEV1",
568 AppId: "app1",
569 ExpireOn: future,
570 ReplaceTag: "u1",
571 Data: payload2,
572 })
573 c.Assert(apiErr, IsNil)
574 c.Check(res, IsNil)
575 c.Check(bsend.err, IsNil)
576 c.Check(bsend.chanId, Equals, store.UnicastInternalChannelId("user1", "DEV1"))
577 c.Check(bsend.top, Equals, int64(0))
578 c.Check(bsend.notifications, HasLen, 1)
579 c.Check(bsend.notifications[0], DeepEquals, protocol.Notification{
580 AppId: "app1",
581 MsgId: "MSG-ID-2",
582 Payload: payload2,
583 })
584 c.Assert(err, IsNil)
585 c.Check(bsend.meta[0], DeepEquals, store.Metadata{
586 Expiration: futureTime,
587 ReplaceTag: "u1",
588 })
589 }
590
591 func (s *handlersSuite) TestDoUnicastWithScrubError(c *C) {
592 sto := &interceptInMemoryPendingStore{
593 store.NewInMemoryPendingStore(),
594 func(meth string, err error) error {
595 if meth == "Scrub" {
596 return errors.New("fail")
597 }
598 return err
599 },
600 }
601 chanId := store.UnicastInternalChannelId("user1", "DEV1")
602 expire := store.Metadata{Expiration: time.Now().Add(4 * time.Hour)}
603 old := store.Metadata{Expiration: time.Now().Add(-1 * time.Hour)}
604 n := json.RawMessage("{}")
605 sto.AppendToUnicastChannel(chanId, "app1", n, "m1", expire)
606 sto.AppendToUnicastChannel(chanId, "app1", n, "m2", old)
607 sto.AppendToUnicastChannel(chanId, "app1", n, "m3", old)
608 sto.AppendToUnicastChannel(chanId, "app1", n, "m4", expire)
609
610 ctx := &context{testStoreAccess(nil), nil, s.testlog}
611 payload := json.RawMessage(`{"a": 1}`)
612 _, apiErr := doUnicast(ctx, sto, &Unicast{
613 UserId: "user1",
614 DeviceId: "DEV1",
615 AppId: "app1",
616 ExpireOn: future,
617 Data: payload,
618 })
619 c.Check(apiErr, Equals, ErrCouldNotStoreNotification)
620 c.Check(s.testlog.Captured(), Equals, "ERROR could not scrub channel: fail\n")
621 }
622
623 func (s *handlersSuite) TestDoUnicastClearPending(c *C) {
624 prevGenMsgId := generateMsgId
625 defer func() {
626 generateMsgId = prevGenMsgId
627 }()
628 generateMsgId = func() string {
629 return "MSG-ID"
630 }
631 sto := store.NewInMemoryPendingStore()
632 chanId := store.UnicastInternalChannelId("user1", "DEV1")
633 expire := store.Metadata{Expiration: time.Now().Add(4 * time.Hour)}
634 n := json.RawMessage("{}")
635 sto.AppendToUnicastChannel(chanId, "app1", n, "m1", expire)
636 sto.AppendToUnicastChannel(chanId, "app1", n, "m2", expire)
637 sto.AppendToUnicastChannel(chanId, "app1", n, "m3", expire)
638 sto.AppendToUnicastChannel(chanId, "app1", n, "m4", expire)
639
640 bsend := &checkBrokerSending{store: sto}
641 ctx := &context{testStoreAccess(nil), bsend, s.testlog}
642 payload := json.RawMessage(`{"a": 1}`)
643 res, apiErr := doUnicast(ctx, sto, &Unicast{
644 UserId: "user1",
645 DeviceId: "DEV1",
646 AppId: "app1",
647 ExpireOn: future,
648 Data: payload,
649 ClearPending: true,
650 })
651 c.Assert(apiErr, IsNil)
652 c.Check(res, IsNil)
653 c.Check(bsend.err, IsNil)
654 c.Check(bsend.chanId, Equals, store.UnicastInternalChannelId("user1", "DEV1"))
655 c.Check(bsend.top, Equals, int64(0))
656 c.Check(bsend.notifications, HasLen, 1)
657 c.Check(bsend.notifications[0], DeepEquals, protocol.Notification{
658 AppId: "app1",
659 MsgId: "MSG-ID",
660 Payload: payload,
661 })
662 }
663
664 func (s *handlersSuite) TestDoUnicastFromTokenFailures(c *C) {
665 fail := errors.New("fail")
666 sto := &interceptInMemoryPendingStore{
667 store.NewInMemoryPendingStore(),
668 func(meth string, err error) error {
669 if meth == "GetInternalChannelIdFromToken" {
670 return fail
671 }
672 return err
673 },
674 }
675 ctx := &context{logger: s.testlog}
676 u := &Unicast{
677 Token: "tok",
678 AppId: "app1",
679 ExpireOn: future,
680 Data: json.RawMessage(`{"a": 1}`),
681 }
682 _, apiErr := doUnicast(ctx, sto, u)
683 c.Check(apiErr, Equals, ErrCouldNotResolveToken)
684 c.Check(s.testlog.Captured(), Equals, "ERROR could not resolve token: fail\n")
685 s.testlog.ResetCapture()
686
687 fail = store.ErrUnknownToken
688 _, apiErr = doUnicast(ctx, sto, u)
689 c.Check(apiErr, Equals, ErrUnknownToken)
690 c.Check(s.testlog.Captured(), Equals, "")
691 fail = store.ErrUnauthorized
692 _, apiErr = doUnicast(ctx, sto, u)
693 c.Check(apiErr, Equals, ErrUnauthorized)
694 c.Check(s.testlog.Captured(), Equals, "")
695 }
696
697 func newPostRequest(path string, message interface{}, server *httptest.Server) *http.Request {
698 packedMessage, err := json.Marshal(message)
699 if err != nil {
700 panic(err)
701 }
702 reader := bytes.NewReader(packedMessage)
703
704 url := server.URL + path
705 request, _ := http.NewRequest("POST", url, reader)
706 request.ContentLength = int64(reader.Len())
707 request.Header.Set("Content-Type", "application/json")
708
709 return request
710 }
711
712 func getResponseBody(response *http.Response) ([]byte, error) {
713 defer response.Body.Close()
714 return ioutil.ReadAll(response.Body)
715 }
716
717 func checkError(c *C, response *http.Response, apiErr *APIError) {
718 c.Check(response.StatusCode, Equals, apiErr.StatusCode)
719 c.Check(response.Header.Get("Content-Type"), Equals, "application/json")
720 error := &APIError{StatusCode: response.StatusCode}
721 body, err := getResponseBody(response)
722 c.Assert(err, IsNil)
723 err = json.Unmarshal(body, error)
724 c.Assert(err, IsNil)
725 c.Check(error, DeepEquals, apiErr)
726 }
727
728 type testBrokerSending struct {
729 chanId chan store.InternalChannelId
730 }
731
732 func (bsend testBrokerSending) Broadcast(chanId store.InternalChannelId) {
733 bsend.chanId <- chanId
734 }
735
736 func (bsend testBrokerSending) Unicast(chanIds ...store.InternalChannelId) {
737 // for now
738 if len(chanIds) != 1 {
739 panic("not expecting many chan ids for now")
740 }
741 bsend.chanId <- chanIds[0]
742 }
743
744 func (s *handlersSuite) TestRespondsToBasicSystemBroadcast(c *C) {
745 sto := store.NewInMemoryPendingStore()
746 storage := testStoreAccess(func(http.ResponseWriter, *http.Request) (store.PendingStore, error) {
747 return sto, nil
748 })
749 bsend := testBrokerSending{make(chan store.InternalChannelId, 1)}
750 testServer := httptest.NewServer(MakeHandlersMux(storage, bsend, nil))
751 defer testServer.Close()
752
753 payload := json.RawMessage(`{"foo":"bar"}`)
754
755 request := newPostRequest("/broadcast", &Broadcast{
756 Channel: "system",
757 ExpireOn: future,
758 Data: payload,
759 }, testServer)
760
761 response, err := s.client.Do(request)
762 c.Assert(err, IsNil)
763
764 c.Check(response.StatusCode, Equals, http.StatusOK)
765 c.Check(response.Header.Get("Content-Type"), Equals, "application/json")
766 body, err := getResponseBody(response)
767 c.Assert(err, IsNil)
768 dest := make(map[string]bool)
769 err = json.Unmarshal(body, &dest)
770 c.Assert(err, IsNil)
771 c.Assert(dest, DeepEquals, map[string]bool{"ok": true})
772
773 top, _, err := sto.GetChannelSnapshot(store.SystemInternalChannelId)
774 c.Assert(err, IsNil)
775 c.Check(top, Equals, int64(1))
776 c.Check(<-bsend.chanId, Equals, store.SystemInternalChannelId)
777 }
778
779 func (s *handlersSuite) TestStoreUnavailable(c *C) {
780 storage := testStoreAccess(func(http.ResponseWriter, *http.Request) (store.PendingStore, error) {
781 return nil, ErrStoreUnavailable
782 })
783 testServer := httptest.NewServer(MakeHandlersMux(storage, nil, nil))
784 defer testServer.Close()
785
786 payload := json.RawMessage(`{"foo":"bar"}`)
787
788 request := newPostRequest("/broadcast", &Broadcast{
789 Channel: "system",
790 ExpireOn: future,
791 Data: payload,
792 }, testServer)
793
794 response, err := s.client.Do(request)
795 c.Assert(err, IsNil)
796 checkError(c, response, ErrStoreUnavailable)
797 }
798
799 func (s *handlersSuite) TestFromBroadcastError(c *C) {
800 sto := store.NewInMemoryPendingStore()
801 storage := testStoreAccess(func(http.ResponseWriter, *http.Request) (store.PendingStore, error) {
802 return sto, nil
803 })
804 testServer := httptest.NewServer(MakeHandlersMux(storage, nil, nil))
805 defer testServer.Close()
806
807 payload := json.RawMessage(`{"foo":"bar"}`)
808
809 request := newPostRequest("/broadcast", &Broadcast{
810 Channel: "unknown",
811 ExpireOn: future,
812 Data: payload,
813 }, testServer)
814
815 response, err := s.client.Do(request)
816 c.Assert(err, IsNil)
817 checkError(c, response, ErrUnknownChannel)
818 }
819
820 func (s *handlersSuite) TestMissingData(c *C) {
821 storage := testStoreAccess(func(http.ResponseWriter, *http.Request) (store.PendingStore, error) {
822 return store.NewInMemoryPendingStore(), nil
823 })
824 ctx := &context{storage, nil, nil}
825 testServer := httptest.NewServer(&JSONPostHandler{
826 context: ctx,
827 parsingBodyObj: func() interface{} { return &Broadcast{} },
828 doHandle: doBroadcast,
829 })
830 defer testServer.Close()
831
832 packedMessage := []byte(`{"channel": "system"}`)
833 reader := bytes.NewReader(packedMessage)
834
835 request, err := http.NewRequest("POST", testServer.URL, reader)
836 c.Assert(err, IsNil)
837 request.ContentLength = int64(len(packedMessage))
838 request.Header.Set("Content-Type", "application/json")
839
840 response, err := s.client.Do(request)
841 c.Assert(err, IsNil)
842 checkError(c, response, ErrMissingData)
843 }
844
845 func (s *handlersSuite) TestCannotBroadcastMalformedData(c *C) {
846 storage := testStoreAccess(func(http.ResponseWriter, *http.Request) (store.PendingStore, error) {
847 return store.NewInMemoryPendingStore(), nil
848 })
849 ctx := &context{storage, nil, nil}
850 testServer := httptest.NewServer(&JSONPostHandler{
851 context: ctx,
852 parsingBodyObj: func() interface{} { return &Broadcast{} },
853 })
854 defer testServer.Close()
855
856 packedMessage := []byte("{some bogus-message: ")
857 reader := bytes.NewReader(packedMessage)
858
859 request, err := http.NewRequest("POST", testServer.URL, reader)
860 c.Assert(err, IsNil)
861 request.ContentLength = int64(len(packedMessage))
862 request.Header.Set("Content-Type", "application/json")
863
864 response, err := s.client.Do(request)
865 c.Assert(err, IsNil)
866 checkError(c, response, ErrMalformedJSONObject)
867 }
868
869 func (s *handlersSuite) TestCannotBroadcastTooBigMessages(c *C) {
870 testServer := httptest.NewServer(&JSONPostHandler{})
871 defer testServer.Close()
872
873 bigString := strings.Repeat("a", MaxRequestBodyBytes)
874 dataString := fmt.Sprintf(`"%v"`, bigString)
875
876 request := newPostRequest("/", &Broadcast{
877 Channel: "some-channel",
878 ExpireOn: future,
879 Data: json.RawMessage([]byte(dataString)),
880 }, testServer)
881
882 response, err := s.client.Do(request)
883 c.Assert(err, IsNil)
884 checkError(c, response, ErrRequestBodyTooLarge)
885 }
886
887 func (s *handlersSuite) TestCannotBroadcastWithoutContentLength(c *C) {
888 testServer := httptest.NewServer(&JSONPostHandler{})
889 defer testServer.Close()
890
891 dataString := `{"foo":"bar"}`
892
893 request := newPostRequest("/", &Broadcast{
894 Channel: "some-channel",
895 ExpireOn: future,
896 Data: json.RawMessage([]byte(dataString)),
897 }, testServer)
898 request.ContentLength = -1
899
900 response, err := s.client.Do(request)
901 c.Assert(err, IsNil)
902 checkError(c, response, ErrNoContentLengthProvided)
903 }
904
905 func (s *handlersSuite) TestCannotBroadcastEmptyMessages(c *C) {
906 testServer := httptest.NewServer(&JSONPostHandler{})
907 defer testServer.Close()
908
909 packedMessage := make([]byte, 0)
910 reader := bytes.NewReader(packedMessage)
911
912 request, err := http.NewRequest("POST", testServer.URL, reader)
913 c.Assert(err, IsNil)
914 request.ContentLength = int64(len(packedMessage))
915 request.Header.Set("Content-Type", "application/json")
916
917 response, err := s.client.Do(request)
918 c.Assert(err, IsNil)
919 checkError(c, response, ErrRequestBodyEmpty)
920 }
921
922 func (s *handlersSuite) TestCannotBroadcastNonJSONMessages(c *C) {
923 testServer := httptest.NewServer(&JSONPostHandler{})
924 defer testServer.Close()
925
926 dataString := `{"foo":"bar"}`
927
928 request := newPostRequest("/", &Broadcast{
929 Channel: "some-channel",
930 ExpireOn: future,
931 Data: json.RawMessage([]byte(dataString)),
932 }, testServer)
933 request.Header.Set("Content-Type", "text/plain")
934
935 response, err := s.client.Do(request)
936 c.Assert(err, IsNil)
937 checkError(c, response, ErrWrongContentType)
938 }
939
940 func (s *handlersSuite) TestContentTypeWithCharset(c *C) {
941 testServer := httptest.NewServer(&JSONPostHandler{})
942 defer testServer.Close()
943
944 dataString := `{"foo":"bar"}`
945
946 request := newPostRequest("/", &Broadcast{
947 Channel: "some-channel",
948 ExpireOn: future,
949 Data: json.RawMessage([]byte(dataString)),
950 }, testServer)
951 request.Header.Set("Content-Type", "application/json; charset=UTF-8")
952 result := checkRequestAsPost(request, 1024)
953 c.Assert(result, IsNil)
954 }
955
956 func (s *handlersSuite) TestCannotBroadcastNonPostMessages(c *C) {
957 testServer := httptest.NewServer(&JSONPostHandler{})
958 defer testServer.Close()
959
960 dataString := `{"foo":"bar"}`
961 packedMessage, err := json.Marshal(&Broadcast{
962 Channel: "some-channel",
963 ExpireOn: future,
964 Data: json.RawMessage([]byte(dataString)),
965 })
966 s.c.Assert(err, IsNil)
967 reader := bytes.NewReader(packedMessage)
968
969 request, err := http.NewRequest("GET", testServer.URL, reader)
970 c.Assert(err, IsNil)
971 request.ContentLength = int64(len(packedMessage))
972 request.Header.Set("Content-Type", "application/json")
973
974 response, err := s.client.Do(request)
975 c.Assert(err, IsNil)
976
977 checkError(c, response, ErrWrongRequestMethod)
978 }
979
980 const OK = `.*"ok":true.*`
981
982 func (s *handlersSuite) TestRespondsUnicast(c *C) {
983 sto := store.NewInMemoryPendingStore()
984 storage := testStoreAccess(func(http.ResponseWriter, *http.Request) (store.PendingStore, error) {
985 return sto, nil
986 })
987 bsend := testBrokerSending{make(chan store.InternalChannelId, 1)}
988 testServer := httptest.NewServer(MakeHandlersMux(storage, bsend, s.testlog))
989 defer testServer.Close()
990
991 payload := json.RawMessage(`{"foo":"bar"}`)
992
993 request := newPostRequest("/notify", &Unicast{
994 UserId: "user2",
995 DeviceId: "dev3",
996 AppId: "app2",
997 ExpireOn: future,
998 Data: payload,
999 }, testServer)
1000
1001 response, err := s.client.Do(request)
1002 c.Assert(err, IsNil)
1003
1004 c.Check(response.StatusCode, Equals, http.StatusOK)
1005 c.Check(response.Header.Get("Content-Type"), Equals, "application/json")
1006 body, err := getResponseBody(response)
1007 c.Assert(err, IsNil)
1008 c.Assert(string(body), Matches, OK)
1009
1010 chanId := store.UnicastInternalChannelId("user2", "dev3")
1011 c.Check(<-bsend.chanId, Equals, chanId)
1012 top, notifications, err := sto.GetChannelSnapshot(chanId)
1013 c.Assert(err, IsNil)
1014 c.Check(top, Equals, int64(0))
1015 c.Check(notifications, HasLen, 1)
1016 }
1017
1018 func (s *handlersSuite) TestCheckRegister(c *C) {
1019 registration := func() *Registration {
1020 return &Registration{
1021 DeviceId: "DEV1",
1022 AppId: "app1",
1023 }
1024 }
1025 reg := registration()
1026 apiErr := checkRegister(reg)
1027 c.Assert(apiErr, IsNil)
1028
1029 reg = registration()
1030 reg.AppId = ""
1031 apiErr = checkRegister(reg)
1032 c.Check(apiErr, Equals, ErrMissingIdField)
1033
1034 reg = registration()
1035 reg.DeviceId = ""
1036 apiErr = checkRegister(reg)
1037 c.Check(apiErr, Equals, ErrMissingIdField)
1038 }
1039
1040 func (s *handlersSuite) TestDoRegisterMissingIdField(c *C) {
1041 sto := store.NewInMemoryPendingStore()
1042 token, apiErr := doRegister(nil, sto, &Registration{})
1043 c.Check(apiErr, Equals, ErrMissingIdField)
1044 c.Check(token, IsNil)
1045 }
1046
1047 func (s *handlersSuite) TestDoRegisterCouldNotMakeToken(c *C) {
1048 sto := &interceptInMemoryPendingStore{
1049 store.NewInMemoryPendingStore(),
1050 func(meth string, err error) error {
1051 if meth == "Register" {
1052 return errors.New("fail")
1053 }
1054 return err
1055 },
1056 }
1057 ctx := &context{logger: s.testlog}
1058 _, apiErr := doRegister(ctx, sto, &Registration{
1059 DeviceId: "DEV1",
1060 AppId: "app1",
1061 })
1062 c.Check(apiErr, Equals, ErrCouldNotMakeToken)
1063 c.Check(s.testlog.Captured(), Equals, "ERROR could not make a token: fail\n")
1064 }
1065
1066 func (s *handlersSuite) TestRespondsToRegisterAndUnicast(c *C) {
1067 sto := store.NewInMemoryPendingStore()
1068 storage := testStoreAccess(func(http.ResponseWriter, *http.Request) (store.PendingStore, error) {
1069 return sto, nil
1070 })
1071 bsend := testBrokerSending{make(chan store.InternalChannelId, 1)}
1072 testServer := httptest.NewServer(MakeHandlersMux(storage, bsend, s.testlog))
1073 defer testServer.Close()
1074
1075 request := newPostRequest("/register", &Registration{
1076 DeviceId: "dev3",
1077 AppId: "app2",
1078 }, testServer)
1079
1080 response, err := s.client.Do(request)
1081 c.Assert(err, IsNil)
1082
1083 c.Check(response.StatusCode, Equals, http.StatusOK)
1084 c.Check(response.Header.Get("Content-Type"), Equals, "application/json")
1085 body, err := getResponseBody(response)
1086 c.Assert(err, IsNil)
1087 c.Assert(string(body), Matches, OK)
1088 var reg map[string]interface{}
1089 err = json.Unmarshal(body, &reg)
1090 c.Assert(err, IsNil)
1091
1092 token, ok := reg["token"].(string)
1093 c.Assert(ok, Equals, true)
1094 c.Check(token, Not(Equals), nil)
1095
1096 payload := json.RawMessage(`{"foo":"bar"}`)
1097
1098 request = newPostRequest("/notify", &Unicast{
1099 Token: token,
1100 AppId: "app2",
1101 ExpireOn: future,
1102 Data: payload,
1103 }, testServer)
1104
1105 response, err = s.client.Do(request)
1106 c.Assert(err, IsNil)
1107
1108 c.Check(response.StatusCode, Equals, http.StatusOK)
1109 c.Check(response.Header.Get("Content-Type"), Equals, "application/json")
1110 body, err = getResponseBody(response)
1111 c.Assert(err, IsNil)
1112 c.Assert(string(body), Matches, OK)
1113
1114 chanId := store.UnicastInternalChannelId("dev3", "dev3")
1115 c.Check(<-bsend.chanId, Equals, chanId)
1116 top, notifications, err := sto.GetChannelSnapshot(chanId)
1117 c.Assert(err, IsNil)
1118 c.Check(top, Equals, int64(0))
1119 c.Check(notifications, HasLen, 1)
1120 }
1121
1122 func (s *handlersSuite) TestRespondsToUnregister(c *C) {
1123 yay := make(chan bool, 1)
1124 sto := &interceptInMemoryPendingStore{
1125 store.NewInMemoryPendingStore(),
1126 func(meth string, err error) error {
1127 if meth == "Unregister" {
1128 yay <- true
1129 }
1130 return err
1131 },
1132 }
1133 storage := testStoreAccess(func(http.ResponseWriter, *http.Request) (store.PendingStore, error) {
1134 return sto, nil
1135 })
1136 bsend := testBrokerSending{make(chan store.InternalChannelId, 1)}
1137 testServer := httptest.NewServer(MakeHandlersMux(storage, bsend, nil))
1138 defer testServer.Close()
1139
1140 request := newPostRequest("/unregister", &Registration{
1141 DeviceId: "dev3",
1142 AppId: "app2",
1143 }, testServer)
1144
1145 response, err := s.client.Do(request)
1146 c.Assert(err, IsNil)
1147
1148 c.Check(response.StatusCode, Equals, http.StatusOK)
1149 c.Check(response.Header.Get("Content-Type"), Equals, "application/json")
1150 body, err := getResponseBody(response)
1151 c.Assert(err, IsNil)
1152 c.Assert(string(body), Matches, OK)
1153 c.Check(yay, HasLen, 1)
1154 }
1155
1156 func (s *handlersSuite) TestDoUnregisterMissingIdField(c *C) {
1157 sto := store.NewInMemoryPendingStore()
1158 token, apiErr := doUnregister(nil, sto, &Registration{})
1159 c.Check(apiErr, Equals, ErrMissingIdField)
1160 c.Check(token, IsNil)
1161 }
1162
1163 func (s *handlersSuite) TestDoUnregisterCouldNotRemoveToken(c *C) {
1164 sto := &interceptInMemoryPendingStore{
1165 store.NewInMemoryPendingStore(),
1166 func(meth string, err error) error {
1167 if meth == "Unregister" {
1168 return errors.New("fail")
1169 }
1170 return err
1171 },
1172 }
1173 ctx := &context{logger: s.testlog}
1174 _, apiErr := doUnregister(ctx, sto, &Registration{
1175 DeviceId: "DEV1",
1176 AppId: "app1",
1177 })
1178 c.Check(apiErr, Equals, ErrCouldNotRemoveToken)
1179 c.Check(s.testlog.Captured(), Equals, "ERROR could not remove token: fail\n")
1180 }