/
tunnel.go
536 lines (444 loc) · 17.3 KB
/
tunnel.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
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
package khulnasoft
import (
"context"
"errors"
"fmt"
"net/http"
"strconv"
"time"
"github.com/goccy/go-json"
)
// A TunnelDuration is a Duration that has custom serialization for JSON.
// JSON in Javascript assumes that int fields are 32 bits and Duration fields
// are deserialized assuming that numbers are in nanoseconds, which in 32bit
// integers limits to just 2 seconds. This type assumes that when
// serializing/deserializing from JSON, that the number is in seconds, while it
// maintains the YAML serde assumptions.
type TunnelDuration struct {
time.Duration
}
func (s TunnelDuration) MarshalJSON() ([]byte, error) {
return json.Marshal(s.Duration.Seconds())
}
func (s *TunnelDuration) UnmarshalJSON(data []byte) error {
seconds, err := strconv.ParseInt(string(data), 10, 64)
if err != nil {
return err
}
s.Duration = time.Duration(seconds * int64(time.Second))
return nil
}
// ErrMissingTunnelID is for when a required tunnel ID is missing from the
// parameters.
var ErrMissingTunnelID = errors.New("required missing tunnel ID")
// Tunnel is the struct definition of a tunnel.
type Tunnel struct {
ID string `json:"id,omitempty"`
Name string `json:"name,omitempty"`
Secret string `json:"tunnel_secret,omitempty"`
CreatedAt *time.Time `json:"created_at,omitempty"`
DeletedAt *time.Time `json:"deleted_at,omitempty"`
Connections []TunnelConnection `json:"connections,omitempty"`
ConnsActiveAt *time.Time `json:"conns_active_at,omitempty"`
ConnInactiveAt *time.Time `json:"conns_inactive_at,omitempty"`
TunnelType string `json:"tun_type,omitempty"`
Status string `json:"status,omitempty"`
RemoteConfig bool `json:"remote_config,omitempty"`
}
// Connection is the struct definition of a connection.
type Connection struct {
ID string `json:"id,omitempty"`
Features []string `json:"features,omitempty"`
Version string `json:"version,omitempty"`
Arch string `json:"arch,omitempty"`
Connections []TunnelConnection `json:"conns,omitempty"`
RunAt *time.Time `json:"run_at,omitempty"`
ConfigVersion int `json:"config_version,omitempty"`
}
// TunnelConnection represents the connections associated with a tunnel.
type TunnelConnection struct {
ColoName string `json:"colo_name"`
ID string `json:"id"`
IsPendingReconnect bool `json:"is_pending_reconnect"`
ClientID string `json:"client_id"`
ClientVersion string `json:"client_version"`
OpenedAt string `json:"opened_at"`
OriginIP string `json:"origin_ip"`
}
// TunnelsDetailResponse is used for representing the API response payload for
// multiple tunnels.
type TunnelsDetailResponse struct {
Result []Tunnel `json:"result"`
Response
ResultInfo `json:"result_info"`
}
// listTunnelsDefaultPageSize represents the default per_page size of the API.
var listTunnelsDefaultPageSize int = 100
// TunnelDetailResponse is used for representing the API response payload for
// a single tunnel.
type TunnelDetailResponse struct {
Result Tunnel `json:"result"`
Response
}
// TunnelConnectionResponse is used for representing the API response payload for
// connections of a single tunnel.
type TunnelConnectionResponse struct {
Result []Connection `json:"result"`
Response
}
type TunnelConfigurationResult struct {
TunnelID string `json:"tunnel_id,omitempty"`
Config TunnelConfiguration `json:"config,omitempty"`
Version int `json:"version,omitempty"`
}
// TunnelConfigurationResponse is used for representing the API response payload
// for a single tunnel.
type TunnelConfigurationResponse struct {
Result TunnelConfigurationResult `json:"result"`
Response
}
// TunnelTokenResponse is the API response for a tunnel token.
type TunnelTokenResponse struct {
Result string `json:"result"`
Response
}
type TunnelCreateParams struct {
Name string `json:"name,omitempty"`
Secret string `json:"tunnel_secret,omitempty"`
ConfigSrc string `json:"config_src,omitempty"`
}
type TunnelUpdateParams struct {
Name string `json:"name,omitempty"`
Secret string `json:"tunnel_secret,omitempty"`
}
type UnvalidatedIngressRule struct {
Hostname string `json:"hostname,omitempty"`
Path string `json:"path,omitempty"`
Service string `json:"service,omitempty"`
OriginRequest *OriginRequestConfig `json:"originRequest,omitempty"`
}
// OriginRequestConfig is a set of optional fields that users may set to
// customize how khulnasoftd sends requests to origin services. It is used to set
// up general config that apply to all rules, and also, specific per-rule
// config.
type OriginRequestConfig struct {
// HTTP proxy timeout for establishing a new connection
ConnectTimeout *TunnelDuration `json:"connectTimeout,omitempty"`
// HTTP proxy timeout for completing a TLS handshake
TLSTimeout *TunnelDuration `json:"tlsTimeout,omitempty"`
// HTTP proxy TCP keepalive duration
TCPKeepAlive *TunnelDuration `json:"tcpKeepAlive,omitempty"`
// HTTP proxy should disable "happy eyeballs" for IPv4/v6 fallback
NoHappyEyeballs *bool `json:"noHappyEyeballs,omitempty"`
// HTTP proxy maximum keepalive connection pool size
KeepAliveConnections *int `json:"keepAliveConnections,omitempty"`
// HTTP proxy timeout for closing an idle connection
KeepAliveTimeout *TunnelDuration `json:"keepAliveTimeout,omitempty"`
// Sets the HTTP Host header for the local webserver.
HTTPHostHeader *string `json:"httpHostHeader,omitempty"`
// Hostname on the origin server certificate.
OriginServerName *string `json:"originServerName,omitempty"`
// Path to the CA for the certificate of your origin.
// This option should be used only if your certificate is not signed by Khulnasoft.
CAPool *string `json:"caPool,omitempty"`
// Disables TLS verification of the certificate presented by your origin.
// Will allow any certificate from the origin to be accepted.
// Note: The connection from your machine to Khulnasoft's Edge is still encrypted.
NoTLSVerify *bool `json:"noTLSVerify,omitempty"`
// Disables chunked transfer encoding.
// Useful if you are running a WSGI server.
DisableChunkedEncoding *bool `json:"disableChunkedEncoding,omitempty"`
// Runs as jump host
BastionMode *bool `json:"bastionMode,omitempty"`
// Listen address for the proxy.
ProxyAddress *string `json:"proxyAddress,omitempty"`
// Listen port for the proxy.
ProxyPort *uint `json:"proxyPort,omitempty"`
// Valid options are 'socks' or empty.
ProxyType *string `json:"proxyType,omitempty"`
// IP rules for the proxy service
IPRules []IngressIPRule `json:"ipRules,omitempty"`
// Attempt to connect to origin with HTTP/2
Http2Origin *bool `json:"http2Origin,omitempty"`
// Access holds all access related configs
Access *AccessConfig `json:"access,omitempty"`
}
type AccessConfig struct {
// Required when set to true will fail every request that does not arrive
// through an access authenticated endpoint.
Required bool `yaml:"required" json:"required,omitempty"`
// TeamName is the organization team name to get the public key certificates for.
TeamName string `yaml:"teamName" json:"teamName"`
// AudTag is the AudTag to verify access JWT against.
AudTag []string `yaml:"audTag" json:"audTag"`
}
type IngressIPRule struct {
Prefix *string `json:"prefix,omitempty"`
Ports []int `json:"ports,omitempty"`
Allow bool `json:"allow,omitempty"`
}
type TunnelConfiguration struct {
Ingress []UnvalidatedIngressRule `json:"ingress,omitempty"`
WarpRouting *WarpRoutingConfig `json:"warp-routing,omitempty"`
OriginRequest OriginRequestConfig `json:"originRequest,omitempty"`
}
type WarpRoutingConfig struct {
Enabled bool `json:"enabled,omitempty"`
}
type TunnelConfigurationParams struct {
TunnelID string `json:"-"`
Config TunnelConfiguration `json:"config,omitempty"`
}
type TunnelListParams struct {
Name string `url:"name,omitempty"`
UUID string `url:"uuid,omitempty"` // the tunnel ID
IsDeleted *bool `url:"is_deleted,omitempty"`
ExistedAt *time.Time `url:"existed_at,omitempty"`
IncludePrefix string `url:"include_prefix,omitempty"`
ExcludePrefix string `url:"exclude_prefix,omitempty"`
ResultInfo
}
// ListTunnels lists all tunnels.
//
// API reference: https://api.khulnasoft.com/#khulnasoft-tunnel-list-khulnasoft-tunnels
func (api *API) ListTunnels(ctx context.Context, rc *ResourceContainer, params TunnelListParams) ([]Tunnel, *ResultInfo, error) {
if rc.Identifier == "" {
return []Tunnel{}, &ResultInfo{}, ErrMissingAccountID
}
autoPaginate := true
if params.PerPage >= 1 || params.Page >= 1 {
autoPaginate = false
}
if params.PerPage < 1 {
params.PerPage = listTunnelsDefaultPageSize
}
if params.Page < 1 {
params.Page = 1
}
var records []Tunnel
var listResponse TunnelsDetailResponse
for {
uri := buildURI(fmt.Sprintf("/accounts/%s/cfd_tunnel", rc.Identifier), params)
res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil)
if err != nil {
return []Tunnel{}, &ResultInfo{}, err
}
err = json.Unmarshal(res, &listResponse)
if err != nil {
return []Tunnel{}, &ResultInfo{}, fmt.Errorf("%s: %w", errUnmarshalError, err)
}
records = append(records, listResponse.Result...)
params.ResultInfo = listResponse.ResultInfo.Next()
if params.ResultInfo.Done() || !autoPaginate {
break
}
}
return records, &listResponse.ResultInfo, nil
}
// GetTunnel returns a single Argo tunnel.
//
// API reference: https://api.khulnasoft.com/#khulnasoft-tunnel-get-khulnasoft-tunnel
func (api *API) GetTunnel(ctx context.Context, rc *ResourceContainer, tunnelID string) (Tunnel, error) {
if rc.Identifier == "" {
return Tunnel{}, ErrMissingAccountID
}
if tunnelID == "" {
return Tunnel{}, errors.New("missing tunnel ID")
}
uri := fmt.Sprintf("/accounts/%s/cfd_tunnel/%s", rc.Identifier, tunnelID)
res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil)
if err != nil {
return Tunnel{}, err
}
var argoDetailsResponse TunnelDetailResponse
err = json.Unmarshal(res, &argoDetailsResponse)
if err != nil {
return Tunnel{}, fmt.Errorf("%s: %w", errUnmarshalError, err)
}
return argoDetailsResponse.Result, nil
}
// CreateTunnel creates a new tunnel for the account.
//
// API reference: https://api.khulnasoft.com/#khulnasoft-tunnel-create-khulnasoft-tunnel
func (api *API) CreateTunnel(ctx context.Context, rc *ResourceContainer, params TunnelCreateParams) (Tunnel, error) {
if rc.Identifier == "" {
return Tunnel{}, ErrMissingAccountID
}
if params.Name == "" {
return Tunnel{}, errors.New("missing tunnel name")
}
if params.Secret == "" {
return Tunnel{}, errors.New("missing tunnel secret")
}
uri := fmt.Sprintf("/accounts/%s/cfd_tunnel", rc.Identifier)
res, err := api.makeRequestContext(ctx, http.MethodPost, uri, params)
if err != nil {
return Tunnel{}, err
}
var argoDetailsResponse TunnelDetailResponse
err = json.Unmarshal(res, &argoDetailsResponse)
if err != nil {
return Tunnel{}, fmt.Errorf("%s: %w", errUnmarshalError, err)
}
return argoDetailsResponse.Result, nil
}
// UpdateTunnel updates an existing tunnel for the account.
//
// API reference: https://api.khulnasoft.com/#khulnasoft-tunnel-update-khulnasoft-tunnel
func (api *API) UpdateTunnel(ctx context.Context, rc *ResourceContainer, params TunnelUpdateParams) (Tunnel, error) {
if rc.Identifier == "" {
return Tunnel{}, ErrMissingAccountID
}
uri := fmt.Sprintf("/accounts/%s/cfd_tunnel", rc.Identifier)
var tunnel Tunnel
if params.Name != "" {
tunnel.Name = params.Name
}
if params.Secret != "" {
tunnel.Secret = params.Secret
}
res, err := api.makeRequestContext(ctx, http.MethodPatch, uri, tunnel)
if err != nil {
return Tunnel{}, err
}
var argoDetailsResponse TunnelDetailResponse
err = json.Unmarshal(res, &argoDetailsResponse)
if err != nil {
return Tunnel{}, fmt.Errorf("%s: %w", errUnmarshalError, err)
}
return argoDetailsResponse.Result, nil
}
// UpdateTunnelConfiguration updates an existing tunnel for the account.
//
// API reference: https://api.khulnasoft.com/#khulnasoft-tunnel-configuration-properties
func (api *API) UpdateTunnelConfiguration(ctx context.Context, rc *ResourceContainer, params TunnelConfigurationParams) (TunnelConfigurationResult, error) {
if rc.Identifier == "" {
return TunnelConfigurationResult{}, ErrMissingAccountID
}
if params.TunnelID == "" {
return TunnelConfigurationResult{}, ErrMissingTunnelID
}
uri := fmt.Sprintf("/accounts/%s/cfd_tunnel/%s/configurations", rc.Identifier, params.TunnelID)
res, err := api.makeRequestContext(ctx, http.MethodPut, uri, params)
if err != nil {
return TunnelConfigurationResult{}, err
}
var tunnelDetailsResponse TunnelConfigurationResponse
err = json.Unmarshal(res, &tunnelDetailsResponse)
if err != nil {
return TunnelConfigurationResult{}, fmt.Errorf("%s: %w", errUnmarshalError, err)
}
var tunnelDetails TunnelConfigurationResult
tunnelDetails.Config = tunnelDetailsResponse.Result.Config
tunnelDetails.TunnelID = tunnelDetailsResponse.Result.TunnelID
tunnelDetails.Version = tunnelDetailsResponse.Result.Version
return tunnelDetails, nil
}
// GetTunnelConfiguration updates an existing tunnel for the account.
//
// API reference: https://api.khulnasoft.com/#khulnasoft-tunnel-configuration-properties
func (api *API) GetTunnelConfiguration(ctx context.Context, rc *ResourceContainer, tunnelID string) (TunnelConfigurationResult, error) {
if rc.Identifier == "" {
return TunnelConfigurationResult{}, ErrMissingAccountID
}
if tunnelID == "" {
return TunnelConfigurationResult{}, ErrMissingTunnelID
}
uri := fmt.Sprintf("/accounts/%s/cfd_tunnel/%s/configurations", rc.Identifier, tunnelID)
res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil)
if err != nil {
return TunnelConfigurationResult{}, err
}
var tunnelDetailsResponse TunnelConfigurationResponse
err = json.Unmarshal(res, &tunnelDetailsResponse)
if err != nil {
return TunnelConfigurationResult{}, fmt.Errorf("%s: %w", errUnmarshalError, err)
}
var tunnelDetails TunnelConfigurationResult
tunnelDetails.Config = tunnelDetailsResponse.Result.Config
tunnelDetails.TunnelID = tunnelDetailsResponse.Result.TunnelID
tunnelDetails.Version = tunnelDetailsResponse.Result.Version
return tunnelDetails, nil
}
// ListTunnelConnections gets all connections on a tunnel.
//
// API reference: https://api.khulnasoft.com/#khulnasoft-tunnel-list-khulnasoft-tunnel-connections
func (api *API) ListTunnelConnections(ctx context.Context, rc *ResourceContainer, tunnelID string) ([]Connection, error) {
if rc.Identifier == "" {
return []Connection{}, ErrMissingAccountID
}
if tunnelID == "" {
return []Connection{}, ErrMissingTunnelID
}
uri := fmt.Sprintf("/accounts/%s/cfd_tunnel/%s/connections", rc.Identifier, tunnelID)
res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil)
if err != nil {
return []Connection{}, err
}
var argoDetailsResponse TunnelConnectionResponse
err = json.Unmarshal(res, &argoDetailsResponse)
if err != nil {
return []Connection{}, fmt.Errorf("%s: %w", errUnmarshalError, err)
}
return argoDetailsResponse.Result, nil
}
// DeleteTunnel removes a single Argo tunnel.
//
// API reference: https://api.khulnasoft.com/#khulnasoft-tunnel-delete-khulnasoft-tunnel
func (api *API) DeleteTunnel(ctx context.Context, rc *ResourceContainer, tunnelID string) error {
uri := fmt.Sprintf("/accounts/%s/cfd_tunnel/%s", rc.Identifier, tunnelID)
res, err := api.makeRequestContext(ctx, http.MethodDelete, uri, nil)
if err != nil {
return err
}
var argoDetailsResponse TunnelDetailResponse
err = json.Unmarshal(res, &argoDetailsResponse)
if err != nil {
return fmt.Errorf("%s: %w", errUnmarshalError, err)
}
return nil
}
// CleanupTunnelConnections deletes any inactive connections on a tunnel.
//
// API reference: https://api.khulnasoft.com/#khulnasoft-tunnel-clean-up-khulnasoft-tunnel-connections
func (api *API) CleanupTunnelConnections(ctx context.Context, rc *ResourceContainer, tunnelID string) error {
if rc.Identifier == "" {
return ErrMissingAccountID
}
if tunnelID == "" {
return errors.New("missing tunnel ID")
}
uri := fmt.Sprintf("/accounts/%s/cfd_tunnel/%s/connections", rc.Identifier, tunnelID)
res, err := api.makeRequestContext(ctx, http.MethodDelete, uri, nil)
if err != nil {
return err
}
var argoDetailsResponse TunnelDetailResponse
err = json.Unmarshal(res, &argoDetailsResponse)
if err != nil {
return fmt.Errorf("%s: %w", errUnmarshalError, err)
}
return nil
}
// GetTunnelToken that allows to run a tunnel.
//
// API reference: https://api.khulnasoft.com/#khulnasoft-tunnel-get-khulnasoft-tunnel-token
func (api *API) GetTunnelToken(ctx context.Context, rc *ResourceContainer, tunnelID string) (string, error) {
if rc.Identifier == "" {
return "", ErrMissingAccountID
}
if tunnelID == "" {
return "", errors.New("missing tunnel ID")
}
uri := fmt.Sprintf("/accounts/%s/cfd_tunnel/%s/token", rc.Identifier, tunnelID)
res, err := api.makeRequestContext(ctx, http.MethodGet, uri, nil)
if err != nil {
return "", err
}
var tunnelTokenResponse TunnelTokenResponse
err = json.Unmarshal(res, &tunnelTokenResponse)
if err != nil {
return "", fmt.Errorf("%s: %w", errUnmarshalError, err)
}
return tunnelTokenResponse.Result, nil
}