-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathclient.go
More file actions
313 lines (271 loc) · 7.64 KB
/
client.go
File metadata and controls
313 lines (271 loc) · 7.64 KB
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
303
304
305
306
307
308
309
310
311
312
313
package client
import (
"context"
"crypto/tls"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"strconv"
"time"
"github.com/coder/websocket"
"github.com/sirupsen/logrus"
"github.com/ClifHouck/unified/types"
)
type Config struct {
// The hostname of the unifi control plane.
Hostname string
// API key issued by unifi control plane. Must be included in requests
// for authorization.
APIKey string
// Controls the interval between keep-alive pings for websocket
// connections.
WebSocketKeepAliveInterval time.Duration
// Controls the configuration of http.Client TLS verification behavior.
InsecureSkipVerify bool
}
func NewDefaultConfig(apiKey string) *Config {
return &Config{
Hostname: "unifi",
APIKey: apiKey,
WebSocketKeepAliveInterval: time.Second * 30,
// Unfortunately, unifi doesn't seem to self-sign for `unifi`, nor
// `192.168.1.1` for that matter.
InsecureSkipVerify: true,
}
}
// IsValid returns true if config is valid, and false otherwise. Also returns a list of
// reasons verification failed.
func (c *Config) IsValid() (bool, []string) {
reasons := []string{}
if c.APIKey == "" {
reasons = append(reasons, "APIKey must not be empty")
}
if c.WebSocketKeepAliveInterval < time.Second {
reasons = append(
reasons,
"WebSocketKeepAliveInterval is too short. Must be longer than one second.",
)
}
if c.WebSocketKeepAliveInterval > time.Minute*10 {
reasons = append(
reasons,
"WebSocketKeepAliveInterval is too long. Must be shorter than ten minutes.",
)
}
valid := len(reasons) == 0
return valid, reasons
}
type Client struct {
ctx context.Context
config *Config
client *http.Client
log *logrus.Logger
Network types.NetworkV1
Protect types.ProtectV1
}
func NewClient(ctx context.Context, config *Config, log *logrus.Logger) *Client {
client := &Client{
ctx: ctx,
config: config,
log: log,
client: &http.Client{
Transport: &http.Transport{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: config.InsecureSkipVerify, //nolint:gosec // TODO: Figure out how to always enable TLS verification!
},
},
},
}
client.Network = &networkV1Client{client: client}
client.Protect = &protectV1Client{client: client}
return client
}
func (c *Client) headers(contentType string) *http.Header {
headers := &http.Header{}
headers.Add("X-Api-Key", c.config.APIKey)
headers.Add("Accept", "application/json")
if contentType != "" {
headers.Add("Content-Type", contentType)
} else {
headers.Add("Content-Type", "application/json")
}
return headers
}
func (c *Client) webSocketHeaders() *http.Header {
headers := &http.Header{}
headers.Add("X-Api-Key", c.config.APIKey)
return headers
}
type apiEndpoint struct {
Application string
ContentType string
Description string
ExpectedStatus int
HasRequestBody bool
Method string
NumQueryArgs int
NumURLArgs int
URLFragment string
}
type requestArgs struct {
Endpoint *apiEndpoint
URLArguments []any
RequestBody io.Reader
Query *url.Values
}
const urlTemplate string = "%s://%s/proxy/%s/integration/v1/%s"
func (c *Client) renderURL(req *requestArgs) string {
renderedFragment := req.Endpoint.URLFragment
if req.Endpoint.NumURLArgs != len(req.URLArguments) {
c.log.WithFields(logrus.Fields{
"expected_args": req.Endpoint.NumURLArgs,
"actual_args": len(req.URLArguments),
"URLFragment": req.Endpoint.URLFragment,
}).Fatal("Number of url arguments does not match number of arguments " +
"required by the API endpoint")
}
if len(req.URLArguments) > 0 {
renderedFragment = fmt.Sprintf(req.Endpoint.URLFragment, req.URLArguments...)
}
url := fmt.Sprintf(
urlTemplate,
"https",
c.config.Hostname,
req.Endpoint.Application,
renderedFragment,
)
// TODO: Some sort of sanity checking on number & keys of query args...
if req.Query != nil {
encodedQuery := req.Query.Encode()
if len(encodedQuery) > 0 {
url = url + "?" + encodedQuery
}
}
c.log.WithFields(logrus.Fields{
"url": url,
}).Trace("Rendered url")
return url
}
func (c *Client) decodeErrorResponse(body []byte) {
var unifiError types.Error
err := json.Unmarshal(body, &unifiError)
switch {
case err == nil && unifiError.StatusCode != 0:
c.log.WithFields(logrus.Fields{
"code": unifiError.StatusCode,
"name": unifiError.StatusName,
"message": unifiError.Message,
}).Error("UniFi application returned an error")
case err == nil && unifiError.StatusCode == 0:
// This is probably an undocumented Protect Error
var protectError types.ProtectErrorMessage
protectErr := json.Unmarshal(body, &protectError)
if protectErr != nil {
c.log.Error("Could not unwrap error message as ProtectErrorMessage")
break
}
c.log.WithFields(logrus.Fields{"code": protectError.Error,
"name": protectError.Name,
"entity": protectError.Entity,
}).Error("UniFi application returned a protect error")
for _, issue := range protectError.Issues {
c.log.WithFields(logrus.Fields{
"instance_path": issue.InstancePath,
"keyword": issue.Keyword,
}).Errorf("Issue with Request: %s", issue.Message)
}
default:
c.log.Debug(string(body))
c.log.Errorf("Could not decode UniFi error despite bad response code: %s", err.Error())
}
}
func (c *Client) doRequest(req *requestArgs) ([]byte, error) {
renderedURL := c.renderURL(req)
if req.Endpoint.HasRequestBody && req.RequestBody == http.NoBody {
c.log.WithFields(logrus.Fields{
"URLFragment": req.Endpoint.URLFragment,
}).Fatal("Request should have a body but http.NoBody was passed")
}
request, err := http.NewRequestWithContext(
c.ctx,
req.Endpoint.Method,
renderedURL,
req.RequestBody,
)
if err != nil {
return nil, err
}
request.Header = *c.headers(req.Endpoint.ContentType)
resp, err := c.client.Do(request)
if err != nil {
return nil, err
}
defer func() {
closeErr := resp.Body.Close()
if closeErr != nil {
c.log.WithFields(logrus.Fields{
"url": renderedURL,
"status": resp.StatusCode,
}).Errorf("Error closing response body: %s", closeErr.Error())
}
}()
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
expectedStatus := req.Endpoint.ExpectedStatus
if expectedStatus == 0 {
expectedStatus = http.StatusOK
}
if resp.StatusCode != expectedStatus {
c.decodeErrorResponse(body)
return nil, fmt.Errorf(
"got unexpected http code %d when requesting '%s'",
resp.StatusCode,
renderedURL,
)
}
c.log.WithFields(logrus.Fields{
"url": renderedURL,
"status": resp.StatusCode,
}).Debug("https request success")
return body, nil
}
// Periodically pings the websocket connection to keep it alive.
// coder/websocket is concurrency-safe for writes so this may be used with
// any websocket connection.
func (c *Client) webSocketKeepAlive(conn *websocket.Conn, url string) {
tickChan := time.Tick(c.config.WebSocketKeepAliveInterval)
for next := range tickChan {
err := conn.Ping(c.ctx)
if err != nil {
c.log.WithFields(logrus.Fields{
"url": url,
"error": err.Error(),
}).Error("WebSocket.Ping returned error")
return
}
c.log.WithFields(logrus.Fields{
"url": url,
"next_ping_at": next,
}).Trace("WebSocket.Ping (Keep-Alive) Success")
}
}
func buildQuery(filter types.Filter, pageArgs *types.PageArguments) *url.Values {
query := &url.Values{}
filterStr := string(filter)
if len(filterStr) > 0 {
query.Add("filter", string(filter))
}
if pageArgs != nil {
if pageArgs.Limit != 0 {
query.Add("limit", strconv.FormatUint(uint64(pageArgs.Limit), 10))
}
if pageArgs.Offset != 0 {
query.Add("offset", strconv.FormatUint(uint64(pageArgs.Offset), 10))
}
}
return query
}