/
endpoints.go
125 lines (101 loc) · 2.8 KB
/
endpoints.go
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
// Copyright (c) Abstract Machines
// SPDX-License-Identifier: Apache-2.0
package api
import (
"context"
"fmt"
"net/http"
"net/url"
"regexp"
"strings"
"github.com/absmach/magistrala/pkg/errors"
"github.com/absmach/magistrala/ws"
"github.com/go-chi/chi/v5"
)
var channelPartRegExp = regexp.MustCompile(`^/channels/([\w\-]+)/messages(/[^?]*)?(\?.*)?$`)
func handshake(ctx context.Context, svc ws.Service) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
req, err := decodeRequest(r)
if err != nil {
encodeError(w, err)
return
}
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
logger.Warn(fmt.Sprintf("Failed to upgrade connection to websocket: %s", err.Error()))
return
}
req.conn = conn
client := ws.NewClient(conn)
if err := svc.Subscribe(ctx, req.thingKey, req.chanID, req.subtopic, client); err != nil {
req.conn.Close()
return
}
logger.Debug(fmt.Sprintf("Successfully upgraded communication to WS on channel %s", req.chanID))
}
}
func decodeRequest(r *http.Request) (connReq, error) {
authKey := r.Header.Get("Authorization")
if authKey == "" {
authKeys := r.URL.Query()["authorization"]
if len(authKeys) == 0 {
logger.Debug("Missing authorization key.")
return connReq{}, errUnauthorizedAccess
}
authKey = authKeys[0]
}
chanID := chi.URLParam(r, "chanID")
req := connReq{
thingKey: authKey,
chanID: chanID,
}
channelParts := channelPartRegExp.FindStringSubmatch(r.RequestURI)
if len(channelParts) < 2 {
logger.Warn("Empty channel id or malformed url")
return connReq{}, errors.ErrMalformedEntity
}
subtopic, err := parseSubTopic(channelParts[2])
if err != nil {
return connReq{}, err
}
req.subtopic = subtopic
return req, nil
}
func parseSubTopic(subtopic string) (string, error) {
if subtopic == "" {
return subtopic, nil
}
subtopic, err := url.QueryUnescape(subtopic)
if err != nil {
return "", errMalformedSubtopic
}
subtopic = strings.ReplaceAll(subtopic, "/", ".")
elems := strings.Split(subtopic, ".")
filteredElems := []string{}
for _, elem := range elems {
if elem == "" {
continue
}
if len(elem) > 1 && (strings.Contains(elem, "*") || strings.Contains(elem, ">")) {
return "", errMalformedSubtopic
}
filteredElems = append(filteredElems, elem)
}
subtopic = strings.Join(filteredElems, ".")
return subtopic, nil
}
func encodeError(w http.ResponseWriter, err error) {
var statusCode int
switch err {
case ws.ErrEmptyID, ws.ErrEmptyTopic:
statusCode = http.StatusBadRequest
case errUnauthorizedAccess:
statusCode = http.StatusForbidden
case errMalformedSubtopic, errors.ErrMalformedEntity:
statusCode = http.StatusBadRequest
default:
statusCode = http.StatusNotFound
}
logger.Warn(fmt.Sprintf("Failed to authorize: %s", err.Error()))
w.WriteHeader(statusCode)
}