-
Notifications
You must be signed in to change notification settings - Fork 5
/
client.go
175 lines (147 loc) · 3.8 KB
/
client.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
package api
import (
"bytes"
"context"
"crypto/tls"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"github.com/hashicorp/go-retryablehttp"
"golang.org/x/text/cases"
"golang.org/x/text/language"
"io"
"log"
"net/http"
"net/http/httputil"
"strings"
"time"
)
const (
clientMaxBackoff = 30
clientMinBackoff = 1
clientMaxRetries = 4
)
var clientMutexKey = "OPNSENSE"
type Client struct {
client *retryablehttp.Client
opts Options
}
type Options struct {
Uri string
APIKey string
APISecret string
AllowInsecure bool
// Retries
MaxBackoff int64
MinBackoff int64
MaxRetries int64
}
func NewClient(options Options) *Client {
client := &Client{
client: retryablehttp.NewClient(),
opts: options,
}
// Configure HTTP client
client.client.HTTPClient.Transport = &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: options.AllowInsecure},
}
// Set defaults for retries
client.client.RetryWaitMax = clientMaxBackoff
client.client.RetryWaitMin = clientMinBackoff
client.client.RetryMax = clientMaxRetries
// Override defaults for retries, if set
if options.MaxBackoff != 0 {
client.client.RetryWaitMax = time.Duration(options.MaxBackoff) * time.Second
}
if options.MinBackoff != 0 {
client.client.RetryWaitMin = time.Duration(options.MinBackoff) * time.Second
}
if options.MaxRetries != 0 {
client.client.RetryMax = int(options.MaxRetries)
}
return client
}
// Requests
func (c *Client) getAuth() string {
auth := c.opts.APIKey + ":" + c.opts.APISecret
return base64.StdEncoding.EncodeToString([]byte(auth))
}
func (c *Client) doRequest(ctx context.Context, method, endpoint string, body any, resp any) error {
// Create IO readers
var bodyReader io.Reader
if body != nil {
// Marshal body into bytes
bodyBytes, err := json.Marshal(body)
if err != nil {
return err
}
// Convert body bytes into reader
bodyReader = bytes.NewReader(bodyBytes)
}
// Create request
req, err := retryablehttp.NewRequestWithContext(ctx, method, fmt.Sprintf("%s/api%s", c.opts.Uri, endpoint), bodyReader)
if err != nil {
return err
}
// Add headers
req.Header.Add("Authorization", fmt.Sprintf("Basic %s", c.getAuth()))
if body != nil {
req.Header.Add("Content-Type", "application/json")
}
// Log request
dReq, _ := httputil.DumpRequest(req.Request, true)
log.Println(fmt.Sprintf("\n%s\n", string(dReq)))
// Do request
res, err := c.client.Do(req)
if err != nil {
return err
}
defer res.Body.Close()
// Log response
dRes, _ := httputil.DumpResponse(res, true)
log.Println(ctx, fmt.Sprintf("\n%s\n", string(dRes)))
// Check for 200
if res.StatusCode != http.StatusOK {
return fmt.Errorf("status code non-200; status code %d", res.StatusCode)
}
// Unmarshal resp JSON data to struct
err = json.NewDecoder(res.Body).Decode(resp)
if err != nil {
return err
}
return nil
}
// ReconfigureService defined at the endpoint.
func (c *Client) ReconfigureService(ctx context.Context, endpoint string) error {
// Handle services without a reconfigure endpoint
if endpoint == "" {
return nil
}
// Send reconfigure request to OPNsense
respJson := &struct {
Status string `json:"status,omitempty"`
Result string `json:"result,omitempty"`
}{}
err := c.doRequest(ctx, "POST", endpoint, nil, respJson)
if err != nil {
return err
}
// Since os-wireguard's reconfigure returns {"result":"ok"}, handle both cases
status := ""
if respJson.Status != "" {
status = respJson.Status
} else if respJson.Result != "" {
status = respJson.Result
} else {
panic(errors.New("reconfigure returned with unknown status response"))
}
// Validate service restarted correctly
status = cases.Lower(language.English).String(
strings.TrimSpace(status),
)
if status != "ok" {
return fmt.Errorf("reconfigure failed. status: %s", status)
}
return nil
}