/
gatewayconn.go
302 lines (261 loc) · 8.39 KB
/
gatewayconn.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
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
296
297
298
299
300
301
302
// +build coap !coap,!http
/*
* Copyright 2020 ForgeRock AS
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package client
import (
"bytes"
"context"
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"runtime"
"strings"
"time"
frcrypto "github.com/ForgeRock/iot-edge/v7/internal/crypto"
"github.com/go-ocf/go-coap"
"github.com/go-ocf/go-coap/codes"
"github.com/pion/dtls/v2"
)
// CoAP Content-Formats registry does not contain a JOSE value, using an unassigned value
const AppJOSE coap.MediaType = 11650
type errCoAPStatusCode struct {
code codes.Code
payload []byte
}
func (e errCoAPStatusCode) Error() string {
msg := fmt.Sprintf("code: %v", e.code)
if e.payload != nil {
msg += fmt.Sprintf(", payload: %s", string(e.payload))
}
return msg
}
// dial returns an existing connection or creates a new one
func (c *gatewayConnection) dial() (*coap.ClientConn, error) {
if c.conn != nil {
return c.conn, nil
}
var err error
c.client.DialTimeout = c.timeout
c.conn, err = c.client.Dial(c.address)
return c.conn, err
}
// context returns a context to be used with CoAP requests
func (c *gatewayConnection) context() (context.Context, context.CancelFunc) {
if c.timeout > 0 {
return context.WithTimeout(context.Background(), c.timeout)
}
return context.WithCancel(context.Background())
}
func dtlsClientConfig(cert ...tls.Certificate) *dtls.Config {
return &dtls.Config{
Certificates: cert,
ExtendedMasterSecret: dtls.RequireExtendedMasterSecret,
InsecureSkipVerify: true,
}
}
// Initialise checks that the server can be reached and prepares the client for further communication
func (c *gatewayConnection) Initialise() (err error) {
// create certificate
cert, err := frcrypto.PublicKeyCertificate(c.key)
if err != nil {
return err
}
c.client = &coap.Client{
Net: "udp-dtls",
DTLSConfig: dtlsClientConfig(cert),
}
conn, err := c.dial()
if err != nil {
return err
}
runtime.SetFinalizer(c, func(c *gatewayConnection) {
c.conn.Close()
})
timeout := c.timeout
if timeout == 0 {
// default ping timeout to an hour
timeout = 3600 * time.Second
}
err = conn.Ping(timeout)
return err
}
// Authenticate with the AM authTree using the given payload
func (c *gatewayConnection) Authenticate(payload AuthenticatePayload) (reply AuthenticatePayload, err error) {
conn, err := c.dial()
if err != nil {
return reply, err
}
requestBody, err := json.Marshal(payload)
if err != nil {
return reply, err
}
msg, err := conn.NewPostRequest("/authenticate", coap.AppJSON, bytes.NewReader(requestBody))
if err != nil {
return reply, err
}
ctx, cancel := c.context()
defer cancel()
response, err := conn.ExchangeWithContext(ctx, msg)
if err != nil {
return reply, err
} else if response.Code() != codes.Valid {
return reply, ResponseError{ResponseCode: CodeUnauthorized}
}
if err = json.Unmarshal(response.Payload(), &reply); err != nil {
return reply, err
}
return reply, nil
}
// AMInfo makes a request to the IoT Gateway for AM related information
func (c *gatewayConnection) AMInfo() (info AMInfoResponse, err error) {
conn, err := c.dial()
if err != nil {
return info, err
}
ctx, cancel := c.context()
defer cancel()
response, err := conn.GetWithContext(ctx, "/aminfo")
if err != nil {
return info, err
} else if response.Code() != codes.Content {
return info, errCoAPStatusCode{response.Code(), response.Payload()}
}
if err = json.Unmarshal(response.Payload(), &info); err != nil {
return info, err
}
return info, nil
}
// AccessToken makes an access token request with the given session token and payload
// SSO token is extracted from signed JWT by IoT Gateway
func (c *gatewayConnection) AccessToken(tokenID string, content ContentType, payload string) (reply []byte, err error) {
return c.makeAuthorisedPost(tokenID, "/accesstoken", content, payload, nil)
}
// IntrospectAccessToken makes a request to the gateway to introspect an access token
func (c *gatewayConnection) IntrospectAccessToken(tokenID string, content ContentType, payload string) (introspection []byte, err error) {
return c.makeAuthorisedPost(tokenID, "/introspect", content, payload, nil)
}
// Attributes makes a thing attributes request with the given payload
// SSO token is extracted from signed JWT by the IoT Gateway
func (c *gatewayConnection) Attributes(tokenID string, content ContentType, payload string, names []string) (reply []byte, err error) {
return c.makeAuthorisedPost(tokenID, "/attributes", content, payload, names)
}
// UserCode makes an user code request with the given session token and payload
// SSO token is extracted from signed JWT by the IoT Gateway
func (c *gatewayConnection) UserCode(tokenID string, content ContentType, payload string) (reply []byte, err error) {
return c.makeAuthorisedPost(tokenID, "/usercode", content, payload, nil)
}
// UserToken makes an user token request with the given session token and payload
// SSO token is extracted from signed JWT by the IoT Gateway
func (c *gatewayConnection) UserToken(tokenID string, content ContentType, payload string) (reply []byte, err error) {
return c.makeAuthorisedPost(tokenID, "/usertoken", content, payload, nil)
}
func (c *gatewayConnection) makeAuthorisedPost(tokenID string, endpoint string, content ContentType, payload string, query []string) (reply []byte, err error) {
conn, err := c.dial()
if err != nil {
return nil, err
}
ctx, cancel := c.context()
defer cancel()
var coapFormat coap.MediaType
switch content {
case ApplicationJOSE:
coapFormat = AppJOSE
case ApplicationJSON:
coapFormat = coap.AppJSON
wrappedPayload := ThingEndpointPayload{
Token: tokenID,
Payload: payload,
}
b, err := json.Marshal(wrappedPayload)
if err != nil {
return nil, err
}
payload = string(b)
}
request, err := conn.NewPostRequest(endpoint, coapFormat, strings.NewReader(payload))
if err != nil {
return nil, err
}
request.SetQuery(query)
response, err := conn.ExchangeWithContext(ctx, request)
if err != nil {
return nil, err
}
return response.Payload(), errorFromCode(response.Code(), response.Payload())
}
// makeSessionRequest sends a request to the session endpoint with the given action
func (c *gatewayConnection) makeSessionRequest(tokenID string, action string) (response coap.Message, err error) {
conn, err := c.dial()
if err != nil {
return response, err
}
ctx, cancel := c.context()
defer cancel()
b, err := json.Marshal(SessionToken{TokenID: tokenID})
if err != nil {
return response, err
}
message, err := conn.NewPostRequest("/session", coap.AppJSON, bytes.NewReader(b))
if err != nil {
return response, err
}
message.SetQueryString(fmt.Sprintf("_action=%s", action))
return conn.ExchangeWithContext(ctx, message)
}
// ValidateSession represented by the given token
func (c *gatewayConnection) ValidateSession(tokenID string) (ok bool, err error) {
response, err := c.makeSessionRequest(tokenID, "validate")
if err != nil {
return false, err
}
switch response.Code() {
case codes.Changed:
return true, nil
case codes.Unauthorized:
return false, nil
default:
return false, errCoAPStatusCode{response.Code(), response.Payload()}
}
}
// LogoutSession represented by the given token
func (c *gatewayConnection) LogoutSession(tokenID string) (err error) {
response, err := c.makeSessionRequest(tokenID, "logout")
if err != nil {
return err
}
switch response.Code() {
case codes.Changed:
return nil
default:
return errCoAPStatusCode{response.Code(), response.Payload()}
}
}
// errorFromCode will check if the CoAP code is one of the mapped ResponseCodes
func errorFromCode(code codes.Code, response []byte) error {
for _, responseCode := range ResponseCodes {
if responseCode.CoAP == code {
if responseCode.Success {
return nil
}
return ResponseError{
ResponseCode: responseCode,
Message: string(response),
}
}
}
return errors.New("CoAP response code not recognised, " + code.String() + ". Response: " + string(response))
}