forked from tailscale/tailscale-client-go
/
client.go
637 lines (522 loc) · 18.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
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
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
// Package tailscale contains a basic implementation of a client for the Tailscale HTTP api. Documentation is here:
// https://github.com/tailscale/tailscale/blob/main/api.md
package tailscale
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"time"
"github.com/tailscale/hujson"
)
type (
// The Client type is used to perform actions against the Tailscale API.
Client struct {
apiKey string
http *http.Client
baseURL *url.URL
tailnet string
}
// The APIError type describes an error as returned by the Tailscale API.
APIError struct {
Message string `json:"message"`
Data []APIErrorData `json:"data"`
status int
}
// The APIErrorData type describes elements of the data field within errors returned by the Tailscale API.
APIErrorData struct {
User string `json:"user"`
Errors []string `json:"errors"`
}
// The ClientOption type is a function that is used to modify a Client.
ClientOption func(c *Client) error
)
const baseURL = "https://api.tailscale.com"
const contentType = "application/json"
// NewClient returns a new instance of the Client type that will perform operations against a chosen tailnet and will
// provide the apiKey for authorization. Additional options can be provided, see ClientOption for more details.
func NewClient(apiKey, tailnet string, options ...ClientOption) (*Client, error) {
u, err := url.Parse(baseURL)
if err != nil {
return nil, err
}
c := &Client{
apiKey: apiKey,
http: &http.Client{Timeout: time.Minute},
baseURL: u,
tailnet: tailnet,
}
for _, option := range options {
if err = option(c); err != nil {
return nil, err
}
}
return c, nil
}
// WithBaseURL sets a custom baseURL for the Tailscale API, this is primarily used for testing purposes.
func WithBaseURL(baseURL string) ClientOption {
return func(c *Client) error {
u, err := url.Parse(baseURL)
if err != nil {
return err
}
c.baseURL = u
return nil
}
}
func (c *Client) buildRequest(ctx context.Context, method, uri string, body interface{}) (*http.Request, error) {
u, err := c.baseURL.Parse(uri)
if err != nil {
return nil, err
}
var bodyBytes []byte
if body != nil {
bodyBytes, err = json.MarshalIndent(body, "", " ")
if err != nil {
return nil, err
}
}
req, err := http.NewRequestWithContext(ctx, method, u.String(), bytes.NewBuffer(bodyBytes))
if err != nil {
return nil, err
}
switch {
case body == nil:
req.Header.Set("Accept", contentType)
default:
req.Header.Set("Content-Type", contentType)
}
req.SetBasicAuth(c.apiKey, "")
return req, nil
}
func (c *Client) performRequest(req *http.Request, out interface{}) error {
res, err := c.http.Do(req)
if err != nil {
return err
}
defer res.Body.Close()
body, err := io.ReadAll(res.Body)
if err != nil {
return err
}
if res.StatusCode >= http.StatusOK && res.StatusCode < http.StatusMultipleChoices {
// If we don't care about the response body, leave. This check is required as some
// API responses have empty bodies, so we don't want to try and standardize them for
// parsing.
if out == nil {
return nil
}
// If we've got hujson back, convert it to JSON, so we can natively parse it.
if !json.Valid(body) {
body, err = hujson.Standardize(body)
if err != nil {
return err
}
}
return json.Unmarshal(body, out)
}
if res.StatusCode != http.StatusOK && res.StatusCode != http.StatusCreated {
var apiErr APIError
if err = json.Unmarshal(body, &apiErr); err != nil {
return err
}
apiErr.status = res.StatusCode
return apiErr
}
return nil
}
func (err APIError) Error() string {
return fmt.Sprintf("%s (%v)", err.Message, err.status)
}
// SetDNSSearchPaths replaces the list of search paths with the list supplied by the user and returns an error otherwise.
func (c *Client) SetDNSSearchPaths(ctx context.Context, searchPaths []string) error {
const uriFmt = "/api/v2/tailnet/%v/dns/searchpaths"
req, err := c.buildRequest(ctx, http.MethodPost, fmt.Sprintf(uriFmt, c.tailnet), map[string][]string{
"searchPaths": searchPaths,
})
if err != nil {
return err
}
return c.performRequest(req, nil)
}
// DNSSearchPaths retrieves the list of search paths that is currently set for the given tailnet.
func (c *Client) DNSSearchPaths(ctx context.Context) ([]string, error) {
const uriFmt = "/api/v2/tailnet/%v/dns/searchpaths"
req, err := c.buildRequest(ctx, http.MethodGet, fmt.Sprintf(uriFmt, c.tailnet), nil)
if err != nil {
return nil, err
}
resp := make(map[string][]string)
if err = c.performRequest(req, &resp); err != nil {
return nil, err
}
return resp["searchPaths"], nil
}
// SetDNSNameservers replaces the list of DNS nameservers for the given tailnet with the list supplied by the user. Note
// that changing the list of DNS nameservers may also affect the status of MagicDNS (if MagicDNS is on).
func (c *Client) SetDNSNameservers(ctx context.Context, dns []string) error {
const uriFmt = "/api/v2/tailnet/%v/dns/nameservers"
req, err := c.buildRequest(ctx, http.MethodPost, fmt.Sprintf(uriFmt, c.tailnet), map[string][]string{
"dns": dns,
})
if err != nil {
return err
}
return c.performRequest(req, nil)
}
// DNSNameservers lists the DNS nameservers for a tailnet
func (c *Client) DNSNameservers(ctx context.Context) ([]string, error) {
const uriFmt = "/api/v2/tailnet/%v/dns/nameservers"
req, err := c.buildRequest(ctx, http.MethodGet, fmt.Sprintf(uriFmt, c.tailnet), nil)
if err != nil {
return nil, err
}
resp := make(map[string][]string)
if err = c.performRequest(req, &resp); err != nil {
return nil, err
}
return resp["dns"], nil
}
type (
ACL struct {
ACLs []ACLEntry `json:"acls" hujson:"ACLs,omitempty"`
AutoApprovers *ACLAutoApprovers `json:"autoapprovers,omitempty" hujson:"AutoApprovers,omitempty"`
Groups map[string][]string `json:"groups,omitempty" hujson:"Groups,omitempty"`
Hosts map[string]string `json:"hosts,omitempty" hujson:"Hosts,omitempty"`
TagOwners map[string][]string `json:"tagowners,omitempty" hujson:"TagOwners,omitempty"`
DERPMap *ACLDERPMap `json:"derpMap,omitempty" hujson:"DerpMap,omitempty"`
Tests []ACLTest `json:"tests,omitempty" hujson:"Tests,omitempty"`
SSH []ACLSSH `json:"ssh,omitempty" hujson:"SSH,omitempty"`
}
ACLAutoApprovers struct {
Routes map[string][]string `json:"routes" hujson:"Routes"`
ExitNode []string `json:"exitNode" hujson:"ExitNode"`
}
ACLEntry struct {
Action string `json:"action" hujson:"Action"`
Ports []string `json:"ports" hujson:"Ports"`
Users []string `json:"users" hujson:"Users"`
Source []string `json:"src" hujson:"Src"`
Destination []string `json:"dst" hujson:"Dst"`
Protocol string `json:"proto" hujson:"Proto"`
}
ACLTest struct {
User string `json:"user" hujson:"User"`
Allow []string `json:"allow" hujson:"Allow"`
Deny []string `json:"deny" hujson:"Deny"`
Source string `json:"src" hujson:"Src"`
Accept []string `json:"accept" hujson:"Accept"`
}
ACLDERPMap struct {
Regions map[int]*ACLDERPRegion `json:"regions" hujson:"Regions"`
OmitDefaultRegions bool `json:"omitDefaultRegions,omitempty" hujson:"OmitDefaultRegions,omitempty"`
}
ACLDERPRegion struct {
RegionID int `json:"regionID" hujson:"RegionID"`
RegionCode string `json:"regionCode" hujson:"RegionCode"`
RegionName string `json:"regionName" hujson:"RegionName"`
Avoid bool `json:"avoid,omitempty" hujson:"Avoid,omitempty"`
Nodes []*ACLDERPNode `json:"nodes" hujson:"Nodes"`
}
ACLDERPNode struct {
Name string `json:"name" hujson:"Name"`
RegionID int `json:"regionID" hujson:"RegionID"`
HostName string `json:"hostName" hujson:"HostName"`
CertName string `json:"certName,omitempty" hujson:"CertName,omitempty"`
IPv4 string `json:"ipv4,omitempty" hujson:"IPv4,omitempty"`
IPv6 string `json:"ipv6,omitempty" hujson:"IPv6,omitempty"`
STUNPort int `json:"stunPort,omitempty" hujson:"STUNPort,omitempty"`
STUNOnly bool `json:"stunOnly,omitempty" hujson:"STUNOnly,omitempty"`
DERPPort int `json:"derpPort,omitempty" hujson:"DERPPort,omitempty"`
InsecureForTests bool `json:"insecureForRests,omitempty" hujson:"InsecureForTests,omitempty"`
STUNTestIP string `json:"stunTestIP,omitempty" hujson:"STUNTestIP,omitempty"`
}
ACLSSH struct {
Action string `json:"action" hujson:"Action"`
Users []string `json:"users" hujson:"Users"`
Source []string `json:"src" hujson:"Src"`
Destination []string `json:"dst" hujson:"Dst"`
CheckPeriod Duration `json:"checkPeriod" hujson:"CheckPeriod"`
}
)
// ACL retrieves the ACL that is currently set for the given tailnet.
func (c *Client) ACL(ctx context.Context) (*ACL, error) {
const uriFmt = "/api/v2/tailnet/%s/acl"
req, err := c.buildRequest(ctx, http.MethodGet, fmt.Sprintf(uriFmt, c.tailnet), nil)
if err != nil {
return nil, err
}
var resp ACL
if err = c.performRequest(req, &resp); err != nil {
return nil, err
}
return &resp, nil
}
// SetACL sets the ACL for the given tailnet.
func (c *Client) SetACL(ctx context.Context, acl ACL) error {
const uriFmt = "/api/v2/tailnet/%s/acl"
req, err := c.buildRequest(ctx, http.MethodPost, fmt.Sprintf(uriFmt, c.tailnet), acl)
if err != nil {
return err
}
return c.performRequest(req, nil)
}
type DNSPreferences struct {
MagicDNS bool `json:"magicDNS"`
}
// DNSPreferences retrieves the DNS preferences that are currently set for the given tailnet. Supply the tailnet of
// interest in the path.
func (c *Client) DNSPreferences(ctx context.Context) (*DNSPreferences, error) {
const uriFmt = "/api/v2/tailnet/%s/dns/preferences"
req, err := c.buildRequest(ctx, http.MethodGet, fmt.Sprintf(uriFmt, c.tailnet), nil)
if err != nil {
return nil, err
}
var resp DNSPreferences
if err = c.performRequest(req, &resp); err != nil {
return nil, err
}
return &resp, nil
}
// SetDNSPreferences replaces the DNS preferences for a tailnet, specifically, the MagicDNS setting. Note that MagicDNS
// is dependent on DNS servers.
func (c *Client) SetDNSPreferences(ctx context.Context, preferences DNSPreferences) error {
const uriFmt = "/api/v2/tailnet/%s/dns/preferences"
req, err := c.buildRequest(ctx, http.MethodPost, fmt.Sprintf(uriFmt, c.tailnet), preferences)
if err != nil {
return nil
}
return c.performRequest(req, nil)
}
type (
DeviceRoutes struct {
Advertised []string `json:"advertisedRoutes"`
Enabled []string `json:"enabledRoutes"`
}
)
// SetDeviceSubnetRoutes sets which subnet routes are enabled to be routed by a device by replacing the existing list
// of subnet routes with the supplied routes. Routes can be enabled without a device advertising them (e.g. for preauth).
func (c *Client) SetDeviceSubnetRoutes(ctx context.Context, deviceID string, routes []string) error {
const uriFmt = "/api/v2/device/%s/routes"
req, err := c.buildRequest(ctx, http.MethodPost, fmt.Sprintf(uriFmt, deviceID), map[string][]string{
"routes": routes,
})
if err != nil {
return err
}
return c.performRequest(req, nil)
}
// DeviceSubnetRoutes Retrieves the list of subnet routes that a device is advertising, as well as those that are
// enabled for it. Enabled routes are not necessarily advertised (e.g. for pre-enabling), and likewise, advertised
// routes are not necessarily enabled.
func (c *Client) DeviceSubnetRoutes(ctx context.Context, deviceID string) (*DeviceRoutes, error) {
const uriFmt = "/api/v2/device/%s/routes"
req, err := c.buildRequest(ctx, http.MethodGet, fmt.Sprintf(uriFmt, deviceID), nil)
if err != nil {
return nil, err
}
var resp DeviceRoutes
if err = c.performRequest(req, &resp); err != nil {
return nil, err
}
return &resp, nil
}
// Time wraps a time and allows for unmarshalling timestamps that represent an empty time as an empty string (e.g "")
// this is used by the tailscale API when it returns devices that have no created date, such as its hello service.
type Time struct {
time.Time
}
// MarshalJSON is an implementation of json.Marshal.
func (t Time) MarshalJSON() ([]byte, error) {
return json.Marshal(t.Time)
}
// UnmarshalJSON unmarshals the content of data as a time.Time, a blank string will keep the time at its zero value.
func (t *Time) UnmarshalJSON(data []byte) error {
if string(data) == `""` {
return nil
}
if err := json.Unmarshal(data, &t.Time); err != nil {
return err
}
return nil
}
type Device struct {
Addresses []string `json:"addresses"`
Name string `json:"name"`
ID string `json:"id"`
Authorized bool `json:"authorized"`
User string `json:"user"`
Tags []string `json:"tags"`
KeyExpiryDisabled bool `json:"keyExpiryDisabled"`
BlocksIncomingConnections bool `json:"blocksIncomingConnections"`
ClientVersion string `json:"clientVersion"`
Created Time `json:"created"`
Expires Time `json:"expires"`
Hostname string `json:"hostname"`
IsExternal bool `json:"isExternal"`
LastSeen Time `json:"lastSeen"`
MachineKey string `json:"machineKey"`
NodeKey string `json:"nodeKey"`
OS string `json:"os"`
UpdateAvailable bool `json:"updateAvailable"`
}
// Devices lists the devices in a tailnet.
func (c *Client) Devices(ctx context.Context) ([]Device, error) {
const uriFmt = "/api/v2/tailnet/%s/devices"
req, err := c.buildRequest(ctx, http.MethodGet, fmt.Sprintf(uriFmt, c.tailnet), nil)
if err != nil {
return nil, err
}
resp := make(map[string][]Device)
if err = c.performRequest(req, &resp); err != nil {
return nil, err
}
return resp["devices"], nil
}
// AuthorizeDevice marks the specified device identifier as authorized to join the tailnet.
func (c *Client) AuthorizeDevice(ctx context.Context, deviceID string) error {
const uriFmt = "/api/v2/device/%s/authorized"
req, err := c.buildRequest(ctx, http.MethodPost, fmt.Sprintf(uriFmt, deviceID), map[string]bool{
"authorized": true,
})
if err != nil {
return err
}
return c.performRequest(req, nil)
}
// DeleteDevice deletes the device given its deviceID.
func (c *Client) DeleteDevice(ctx context.Context, deviceID string) error {
const uriFmt = "/api/v2/device/%s"
req, err := c.buildRequest(ctx, http.MethodDelete, fmt.Sprintf(uriFmt, deviceID), nil)
if err != nil {
return err
}
return c.performRequest(req, nil)
}
type (
// The KeyCapabilities type describes the capabilities of an authentication key.
KeyCapabilities struct {
Devices struct {
Create struct {
Reusable bool `json:"reusable"`
Ephemeral bool `json:"ephemeral"`
Tags []string `json:"tags"`
Preauthorized bool `json:"preauthorized"`
} `json:"create"`
} `json:"devices"`
}
// The Key type describes an authentication key within the tailnet.
Key struct {
ID string `json:"id"`
Key string `json:"key"`
Created time.Time `json:"created"`
Expires time.Time `json:"expires"`
Capabilities KeyCapabilities `json:"capabilities"`
}
)
// CreateKey creates a new authentication key with the capabilities selected via the KeyCapabilities type. Returns
// the generated key if successful.
func (c *Client) CreateKey(ctx context.Context, capabilities KeyCapabilities) (Key, error) {
const uriFmt = "/api/v2/tailnet/%s/keys"
req, err := c.buildRequest(ctx, http.MethodPost, fmt.Sprintf(uriFmt, c.tailnet), map[string]KeyCapabilities{
"capabilities": capabilities,
})
if err != nil {
return Key{}, err
}
var key Key
return key, c.performRequest(req, &key)
}
// GetKey returns all information on a key whose identifier matches the one provided. This will not return the
// authentication key itself, just the metadata.
func (c *Client) GetKey(ctx context.Context, id string) (Key, error) {
const uriFmt = "/api/v2/tailnet/%s/keys/%s"
req, err := c.buildRequest(ctx, http.MethodGet, fmt.Sprintf(uriFmt, c.tailnet, id), nil)
if err != nil {
return Key{}, err
}
var key Key
return key, c.performRequest(req, &key)
}
// DeleteKey removes an authentication key from the tailnet.
func (c *Client) DeleteKey(ctx context.Context, id string) error {
const uriFmt = "/api/v2/tailnet/%s/keys/%s"
req, err := c.buildRequest(ctx, http.MethodDelete, fmt.Sprintf(uriFmt, c.tailnet, id), nil)
if err != nil {
return err
}
return c.performRequest(req, nil)
}
// SetDeviceTags updates the tags of a target device.
func (c *Client) SetDeviceTags(ctx context.Context, deviceID string, tags []string) error {
const uriFmt = "/api/v2/device/%s/tags"
req, err := c.buildRequest(ctx, http.MethodPost, fmt.Sprintf(uriFmt, deviceID), map[string][]string{
"tags": tags,
})
if err != nil {
return err
}
return c.performRequest(req, nil)
}
type (
// The DeviceKey type represents the properties of the key of an individual device within
// the tailnet.
DeviceKey struct {
KeyExpiryDisabled bool `json:"keyExpiryDisabled"` // Whether or not this device's key will ever expire.
}
)
// SetDeviceKey updates the properties of a device's key.
func (c *Client) SetDeviceKey(ctx context.Context, deviceID string, key DeviceKey) error {
const uriFmt = "/api/v2/device/%s/key"
req, err := c.buildRequest(ctx, http.MethodPost, fmt.Sprintf(uriFmt, deviceID), key)
if err != nil {
return err
}
return c.performRequest(req, nil)
}
// IsNotFound returns true if the provided error implementation is an APIError with a status of 404.
func IsNotFound(err error) bool {
var apiErr APIError
if errors.As(err, &apiErr) {
return apiErr.status == http.StatusNotFound
}
return false
}
// ErrorData returns the contents of the APIError.Data field from the provided error if it is of type APIError. Returns
// a nil slice if the given error is not of type APIError.
func ErrorData(err error) []APIErrorData {
var apiErr APIError
if errors.As(err, &apiErr) {
return apiErr.Data
}
return nil
}
// The Duration type wraps a time.Duration, allowing it to be JSON marshalled as a string like "20h" rather than
// a numeric value.
type Duration struct {
time.Duration
}
// MarshalJSON is an implementation of json.Marshal.
func (d Duration) MarshalJSON() ([]byte, error) {
return json.Marshal(d.Duration.String())
}
// UnmarshalJSON unmarshals the content of data as a time.Duration, a blank string will keep the duration at its zero value.
func (d *Duration) UnmarshalJSON(data []byte) error {
if string(data) == `""` {
return nil
}
var str string
if err := json.Unmarshal(data, &str); err != nil {
return err
}
dur, err := time.ParseDuration(str)
if err != nil {
return err
}
d.Duration = dur
return nil
}