Debian Codegraph @

server/api/handlers.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 has code that offers a REST API for the applications that
18 // want to push messages.
19 package api
20
21 import (
22 "encoding/base64"
23 "encoding/json"
24 "fmt"
25 "io"
26 "mime"
27 "net/http"
28 "time"
29
30 "github.com/google/uuid"
31
32 "gitlab.com/ubports/development/core/lomiri-push-service/logger"
33 "gitlab.com/ubports/development/core/lomiri-push-service/protocol"
34 "gitlab.com/ubports/development/core/lomiri-push-service/server/broker"
35 "gitlab.com/ubports/development/core/lomiri-push-service/server/store"
36 )
37
38 const MaxRequestBodyBytes = 6 * 1024
39 const JSONMediaType = "application/json"
40 const MaxUnicastPayload = 4 * 1024
41
42 // APIError represents a API error (both internally and as JSON in a response).
43 type APIError struct {
44 // http status code
45 StatusCode int `json:"-"`
46 // machine readable label
47 ErrorLabel string `json:"error"`
48 // human message
49 Message string `json:"message"`
50 // extra information
51 Extra json.RawMessage `json:"extra,omitempty"`
52 }
53
54 // machine readable error labels
55 const (
56 ioError = "io-error"
57 invalidRequest = "invalid-request"
58 unknownChannel = "unknown-channel"
59 unknownToken = "unknown-token"
60 unauthorized = "unauthorized"
61 unavailable = "unavailable"
62 internalError = "internal"
63 tooManyPending = "too-many-pending"
64 )
65
66 func (apiErr *APIError) Error() string {
67 return fmt.Sprintf("api %s: %s", apiErr.ErrorLabel, apiErr.Message)
68 }
69
70 // Well-known prebuilt API errors
71 var (
72 ErrNoContentLengthProvided = &APIError{
73 http.StatusLengthRequired,
74 invalidRequest,
75 "A Content-Length must be provided",
76 nil,
77 }
78 ErrRequestBodyEmpty = &APIError{
79 http.StatusBadRequest,
80 invalidRequest,
81 "Request body empty",
82 nil,
83 }
84 ErrRequestBodyTooLarge = &APIError{
85 http.StatusRequestEntityTooLarge,
86 invalidRequest,
87 "Request body too large",
88 nil,
89 }
90 ErrWrongContentType = &APIError{
91 http.StatusUnsupportedMediaType,
92 invalidRequest,
93 "Wrong content type, should be application/json",
94 nil,
95 }
96 ErrWrongRequestMethod = &APIError{
97 http.StatusMethodNotAllowed,
98 invalidRequest,
99 "Wrong request method, should be POST",
100 nil,
101 }
102 ErrWrongRequestMethodGET = &APIError{
103 http.StatusMethodNotAllowed,
104 invalidRequest,
105 "Wrong request method, should be GET",
106 nil,
107 }
108 ErrMalformedJSONObject = &APIError{
109 http.StatusBadRequest,
110 invalidRequest,
111 "Malformed JSON Object",
112 nil,
113 }
114 ErrCouldNotReadBody = &APIError{
115 http.StatusBadRequest,
116 ioError,
117 "Could not read request body",
118 nil,
119 }
120 ErrMissingIdField = &APIError{
121 http.StatusBadRequest,
122 invalidRequest,
123 "Missing id field",
124 nil,
125 }
126 ErrMissingData = &APIError{
127 http.StatusBadRequest,
128 invalidRequest,
129 "Missing data field",
130 nil,
131 }
132 ErrDataTooLarge = &APIError{
133 http.StatusBadRequest,
134 invalidRequest,
135 "Data too large",
136 nil,
137 }
138 ErrInvalidExpiration = &APIError{
139 http.StatusBadRequest,
140 invalidRequest,
141 "Invalid expiration date",
142 nil,
143 }
144 ErrPastExpiration = &APIError{
145 http.StatusBadRequest,
146 invalidRequest,
147 "Past expiration date",
148 nil,
149 }
150 ErrUnknownChannel = &APIError{
151 http.StatusBadRequest,
152 unknownChannel,
153 "Unknown channel",
154 nil,
155 }
156 ErrUnknownToken = &APIError{
157 http.StatusBadRequest,
158 unknownToken,
159 "Unknown token",
160 nil,
161 }
162 ErrUnknown = &APIError{
163 http.StatusInternalServerError,
164 internalError,
165 "Unknown error",
166 nil,
167 }
168 ErrStoreUnavailable = &APIError{
169 http.StatusServiceUnavailable,
170 unavailable,
171 "Message store unavailable",
172 nil,
173 }
174 ErrCouldNotStoreNotification = &APIError{
175 http.StatusServiceUnavailable,
176 unavailable,
177 "Could not store notification",
178 nil,
179 }
180 ErrCouldNotMakeToken = &APIError{
181 http.StatusServiceUnavailable,
182 unavailable,
183 "Could not make token",
184 nil,
185 }
186 ErrCouldNotRemoveToken = &APIError{
187 http.StatusServiceUnavailable,
188 unavailable,
189 "Could not remove token",
190 nil,
191 }
192 ErrCouldNotResolveToken = &APIError{
193 http.StatusServiceUnavailable,
194 unavailable,
195 "Could not resolve token",
196 nil,
197 }
198 ErrUnauthorized = &APIError{
199 http.StatusUnauthorized,
200 unauthorized,
201 "Unauthorized",
202 nil,
203 }
204 ErrTooManyPendingNotifications = &APIError{
205 http.StatusRequestEntityTooLarge,
206 tooManyPending,
207 "Too many pending notifications for this application",
208 nil,
209 }
210 )
211
212 func apiErrorWithExtra(apiErr *APIError, extra interface{}) *APIError {
213 var clone APIError = *apiErr
214 b, err := json.Marshal(extra)
215 if err != nil {
216 panic(fmt.Errorf("couldn't marshal our own errors: %v", err))
217 }
218 clone.Extra = json.RawMessage(b)
219 return &clone
220 }
221
222 type Registration struct {
223 DeviceId string `json:"deviceid"`
224 AppId string `json:"appid"`
225 }
226
227 type Unicast struct {
228 Token string `json:"token"`
229 UserId string `json:"userid"` // not part of the official API
230 DeviceId string `json:"deviceid"` // not part of the official API
231 AppId string `json:"appid"`
232 ExpireOn string `json:"expire_on"`
233 Data json.RawMessage `json:"data"`
234 // clear all pending messages for appid
235 ClearPending bool `json:"clear_pending,omitempty"`
236 // replace pending messages with the same replace_tag
237 ReplaceTag string `json:"replace_tag,omitempty"`
238 }
239
240 // Broadcast request JSON object.
241 type Broadcast struct {
242 Channel string `json:"channel"`
243 ExpireOn string `json:"expire_on"`
244 Data json.RawMessage `json:"data"`
245 }
246
247 // RespondError writes back a JSON error response for a APIError.
248 func RespondError(writer http.ResponseWriter, apiErr *APIError) {
249 wireError, err := json.Marshal(apiErr)
250 if err != nil {
251 panic(fmt.Errorf("couldn't marshal our own errors: %v", err))
252 }
253 writer.Header().Set("Content-type", JSONMediaType)
254 writer.WriteHeader(apiErr.StatusCode)
255 writer.Write(wireError)
256 }
257
258 func checkContentLength(request *http.Request, maxBodySize int64) *APIError {
259 if request.ContentLength == -1 {
260 return ErrNoContentLengthProvided
261 }
262 if request.ContentLength == 0 {
263 return ErrRequestBodyEmpty
264 }
265 if request.ContentLength > maxBodySize {
266 return ErrRequestBodyTooLarge
267 }
268 return nil
269 }
270
271 func checkRequestAsPost(request *http.Request, maxBodySize int64) *APIError {
272 if request.Method != "POST" {
273 return ErrWrongRequestMethod
274 }
275 if err := checkContentLength(request, maxBodySize); err != nil {
276 return err
277 }
278 mediaType, _, err := mime.ParseMediaType(request.Header.Get("Content-Type"))
279 if err != nil || mediaType != JSONMediaType {
280 return ErrWrongContentType
281 }
282 return nil
283 }
284
285 // ReadBody checks that a POST request is well-formed and reads its body.
286 func ReadBody(request *http.Request, maxBodySize int64) ([]byte, *APIError) {
287 if err := checkRequestAsPost(request, maxBodySize); err != nil {
288 return nil, err
289 }
290
291 body := make([]byte, request.ContentLength)
292 _, err := io.ReadFull(request.Body, body)
293
294 if err != nil {
295 return nil, ErrCouldNotReadBody
296 }
297
298 return body, nil
299 }
300
301 var zeroTime = time.Time{}
302
303 func checkCastCommon(data json.RawMessage, expireOn string) (time.Time, *APIError) {
304 if len(data) == 0 {
305 return zeroTime, ErrMissingData
306 }
307 expire, err := time.Parse(time.RFC3339, expireOn)
308 if err != nil {
309 return zeroTime, ErrInvalidExpiration
310 }
311 if expire.Before(time.Now()) {
312 return zeroTime, ErrPastExpiration
313 }
314 return expire, nil
315 }
316
317 func checkBroadcast(bcast *Broadcast) (time.Time, *APIError) {
318 return checkCastCommon(bcast.Data, bcast.ExpireOn)
319 }
320
321 // StoreAccess lets get a notification pending store and parameters
322 // for storage.
323 type StoreAccess interface {
324 // StoreForRequest gets a pending store for the request.
325 StoreForRequest(w http.ResponseWriter, request *http.Request) (store.PendingStore, error)
326 // GetMaxNotificationsPerApplication gets the maximum number
327 // of pending notifications allowed for a signle application.
328 GetMaxNotificationsPerApplication() int
329 }
330
331 // context holds the interfaces to delegate to serving requests
332 type context struct {
333 storage StoreAccess
334 broker broker.BrokerSending
335 logger logger.Logger
336 }
337
338 func (ctx *context) getStore(w http.ResponseWriter, request *http.Request) (store.PendingStore, *APIError) {
339 sto, err := ctx.storage.StoreForRequest(w, request)
340 if err != nil {
341 apiErr, ok := err.(*APIError)
342 if ok {
343 return nil, apiErr
344 }
345 ctx.logger.Errorf("failed to get store: %v", err)
346 return nil, ErrUnknown
347 }
348 return sto, nil
349 }
350
351 // JSONPostHandler is able to handle POST requests with a JSON body
352 // delegating for the actual details.
353 type JSONPostHandler struct {
354 *context
355 parsingBodyObj func() interface{}
356 doHandle func(ctx *context, sto store.PendingStore, parsedBodyObj interface{}) (map[string]interface{}, *APIError)
357 }
358
359 func (h *JSONPostHandler) prepare(w http.ResponseWriter, request *http.Request) (interface{}, store.PendingStore, *APIError) {
360 body, apiErr := ReadBody(request, MaxRequestBodyBytes)
361 if apiErr != nil {
362 return nil, nil, apiErr
363 }
364
365 parsedBodyObj := h.parsingBodyObj()
366 err := json.Unmarshal(body, parsedBodyObj)
367 if err != nil {
368 return nil, nil, ErrMalformedJSONObject
369 }
370
371 sto, apiErr := h.getStore(w, request)
372 if apiErr != nil {
373 return nil, nil, apiErr
374 }
375 return parsedBodyObj, sto, nil
376 }
377
378 func (h *JSONPostHandler) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
379 var apiErr *APIError
380 defer func() {
381 if apiErr != nil {
382 RespondError(writer, apiErr)
383 }
384 }()
385
386 parsedBodyObj, sto, apiErr := h.prepare(writer, request)
387 if apiErr != nil {
388 return
389 }
390 defer sto.Close()
391
392 res, apiErr := h.doHandle(h.context, sto, parsedBodyObj)
393 if apiErr != nil {
394 return
395 }
396
397 writer.Header().Set("Content-Type", "application/json")
398 if res == nil {
399 fmt.Fprintf(writer, `{"ok":true}`)
400 } else {
401 res["ok"] = true
402 resp, err := json.Marshal(res)
403 if err != nil {
404 panic(fmt.Errorf("couldn't marshal our own response: %v", err))
405 }
406 writer.Write(resp)
407 }
408 }
409
410 func doBroadcast(ctx *context, sto store.PendingStore, parsedBodyObj interface{}) (map[string]interface{}, *APIError) {
411 bcast := parsedBodyObj.(*Broadcast)
412 expire, apiErr := checkBroadcast(bcast)
413 if apiErr != nil {
414 return nil, apiErr
415 }
416 chanId, err := sto.GetInternalChannelId(bcast.Channel)
417 if err != nil {
418 switch err {
419 case store.ErrUnknownChannel:
420 return nil, ErrUnknownChannel
421 default:
422 return nil, ErrUnknown
423 }
424 }
425 err = sto.AppendToChannel(chanId, bcast.Data, expire)
426 if err != nil {
427 ctx.logger.Errorf("could not store notification: %v", err)
428 return nil, ErrCouldNotStoreNotification
429 }
430
431 ctx.broker.Broadcast(chanId)
432 return nil, nil
433 }
434
435 func checkUnicast(ucast *Unicast) (time.Time, *APIError) {
436 if ucast.AppId == "" {
437 return zeroTime, ErrMissingIdField
438 }
439 if ucast.Token == "" && (ucast.UserId == "" || ucast.DeviceId == "") {
440 return zeroTime, ErrMissingIdField
441 }
442 if len(ucast.Data) > MaxUnicastPayload {
443 return zeroTime, ErrDataTooLarge
444 }
445 return checkCastCommon(ucast.Data, ucast.ExpireOn)
446 }
447
448 // use a base64 encoded TimeUUID
449 var generateMsgId = func() string {
450 u := uuid.Must(uuid.NewUUID())
451 return base64.StdEncoding.EncodeToString(u[:])
452 }
453
454 func doUnicast(ctx *context, sto store.PendingStore, parsedBodyObj interface{}) (map[string]interface{}, *APIError) {
455 ucast := parsedBodyObj.(*Unicast)
456 expire, apiErr := checkUnicast(ucast)
457 if apiErr != nil {
458 return nil, apiErr
459 }
460
461 chanId, err := sto.GetInternalChannelIdFromToken(ucast.Token, ucast.AppId, ucast.UserId, ucast.DeviceId)
462 if err != nil {
463 switch err {
464 case store.ErrUnknownToken:
465 ctx.logger.Debugf("notify: %v %v unknown", ucast.AppId, ucast.Token)
466 return nil, ErrUnknownToken
467 case store.ErrUnauthorized:
468 ctx.logger.Debugf("notify: %v %v unauthorized", ucast.AppId, ucast.Token)
469 return nil, ErrUnauthorized
470 default:
471 ctx.logger.Errorf("could not resolve token: %v", err)
472 return nil, ErrCouldNotResolveToken
473 }
474 }
475 ctx.logger.Infof("notify: %v %v -> %v", ucast.AppId, ucast.Token, chanId)
476
477 _, notifs, meta, err := sto.GetChannelUnfiltered(chanId)
478 if err != nil {
479 ctx.logger.Errorf("could not peek at notifications: %v", err)
480 return nil, ErrCouldNotStoreNotification
481 }
482 expired := 0
483 replaceable := 0
484 forApp := 0
485 replaceTag := ucast.ReplaceTag
486 scrubCriteria := []string(nil)
487 now := time.Now()
488 var last *protocol.Notification
489 for i, notif := range notifs {
490 if meta[i].Before(now) {
491 expired++
492 continue
493 }
494 if notif.AppId == ucast.AppId {
495 if replaceTag != "" && replaceTag == meta[i].ReplaceTag {
496 // this we will scrub
497 replaceable++
498 continue
499 }
500 forApp++
501 }
502 last = &notif
503 }
504 if ucast.ClearPending {
505 scrubCriteria = []string{ucast.AppId}
506 } else if forApp >= ctx.storage.GetMaxNotificationsPerApplication() {
507 ctx.logger.Debugf("notify: %v %v too many pending", ucast.AppId, chanId)
508 return nil, apiErrorWithExtra(ErrTooManyPendingNotifications,
509 &last.Payload)
510 } else if replaceable > 0 {
511 scrubCriteria = []string{ucast.AppId, replaceTag}
512 }
513 if expired > 0 || scrubCriteria != nil {
514 err := sto.Scrub(chanId, scrubCriteria...)
515 if err != nil {
516 ctx.logger.Errorf("could not scrub channel: %v", err)
517 return nil, ErrCouldNotStoreNotification
518 }
519 }
520
521 msgId := generateMsgId()
522
523 meta1 := store.Metadata{
524 Expiration: expire,
525 ReplaceTag: ucast.ReplaceTag,
526 }
527 err = sto.AppendToUnicastChannel(chanId, ucast.AppId, ucast.Data, msgId, meta1)
528 if err != nil {
529 ctx.logger.Errorf("could not store notification: %v", err)
530 return nil, ErrCouldNotStoreNotification
531 }
532
533 ctx.broker.Unicast(chanId)
534
535 ctx.logger.Debugf("notify: ok %v %v id:%v clear:%v replace:%v expired:%v", ucast.AppId, chanId, msgId, ucast.ClearPending, replaceable, expired)
536 return nil, nil
537 }
538
539 func checkRegister(reg *Registration) *APIError {
540 if reg.DeviceId == "" || reg.AppId == "" {
541 return ErrMissingIdField
542 }
543 return nil
544 }
545
546 func doRegister(ctx *context, sto store.PendingStore, parsedBodyObj interface{}) (map[string]interface{}, *APIError) {
547 reg := parsedBodyObj.(*Registration)
548 apiErr := checkRegister(reg)
549 if apiErr != nil {
550 return nil, apiErr
551 }
552 token, err := sto.Register(reg.DeviceId, reg.AppId)
553 if err != nil {
554 ctx.logger.Errorf("could not make a token: %v", err)
555 return nil, ErrCouldNotMakeToken
556 }
557 return map[string]interface{}{"token": token}, nil
558 }
559
560 func doUnregister(ctx *context, sto store.PendingStore, parsedBodyObj interface{}) (map[string]interface{}, *APIError) {
561 reg := parsedBodyObj.(*Registration)
562 apiErr := checkRegister(reg)
563 if apiErr != nil {
564 return nil, apiErr
565 }
566 err := sto.Unregister(reg.DeviceId, reg.AppId)
567 if err != nil {
568 ctx.logger.Errorf("could not remove token: %v", err)
569 return nil, ErrCouldNotRemoveToken
570 }
571 return nil, nil
572 }
573
574 // MakeHandlersMux makes a handler that dispatches for the various API endpoints.
575 func MakeHandlersMux(storage StoreAccess, broker broker.BrokerSending, logger logger.Logger) *http.ServeMux {
576 ctx := &context{
577 storage: storage,
578 broker: broker,
579 logger: logger,
580 }
581 mux := http.NewServeMux()
582 mux.Handle("/broadcast", &JSONPostHandler{
583 context: ctx,
584 parsingBodyObj: func() interface{} { return &Broadcast{} },
585 doHandle: doBroadcast,
586 })
587 mux.Handle("/notify", &JSONPostHandler{
588 context: ctx,
589 parsingBodyObj: func() interface{} { return &Unicast{} },
590 doHandle: doUnicast,
591 })
592 mux.Handle("/register", &JSONPostHandler{
593 context: ctx,
594 parsingBodyObj: func() interface{} { return &Registration{} },
595 doHandle: doRegister,
596 })
597 mux.Handle("/unregister", &JSONPostHandler{
598 context: ctx,
599 parsingBodyObj: func() interface{} { return &Registration{} },
600 doHandle: doUnregister,
601 })
602 return mux
603 }