-
Notifications
You must be signed in to change notification settings - Fork 147
/
api.go
189 lines (162 loc) · 6.28 KB
/
api.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
package mutagenio
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"github.com/mutagen-io/mutagen/pkg/mutagen"
)
const (
// apiEndpoint is the mutagen.io API endpoint.
apiEndpoint = "https://api.mutagen.io/v1/"
// apiEndpoint is the development API endpoint.
apiEndpointDevelopment = "http://localhost:8081/v1/"
)
// unexpectedResponseStatusError is an error type returned from callAPI if the
// response status returned from the server did not match what was expected.
type unexpectedResponseStatusError struct {
// status is the returned status.
status int
}
// Error implements error.Error.
func (e *unexpectedResponseStatusError) Error() string {
return fmt.Sprintf("unexpected response status: %d %s", e.status, http.StatusText(e.status))
}
var (
// ErrUnauthorized is a sentinel error returned if an API endpoint returns
// a 401 (Unauthorized) status code.
ErrUnauthorized = errors.New("unauthorized")
)
// callAPI performs an API request using the specified parameters.
func callAPI(ctx context.Context, method, resource, token string, request, response interface{}, expectedStatus int) error {
// Create a buffer for the body and encode the request object into it.
body := &bytes.Buffer{}
encoder := json.NewEncoder(body)
if err := encoder.Encode(request); err != nil {
return fmt.Errorf("unable to encode request body: %w", err)
}
// Compute the API endpoint.
apiEndpoint := apiEndpoint
if mutagen.DevelopmentModeEnabled {
apiEndpoint = apiEndpointDevelopment
}
// Create the request.
httpRequest, err := http.NewRequestWithContext(ctx, method, apiEndpoint+resource, body)
if err != nil {
return fmt.Errorf("unable to create request: %w", err)
}
// Set the authorization header.
httpRequest.Header.Set("Authorization", "Bearer "+token)
// Perform the request and (if successful) ensure the response body is
// closed.
httpResponse, err := http.DefaultClient.Do(httpRequest)
if err != nil {
return fmt.Errorf("unable to perform request: %w", err)
}
defer httpResponse.Body.Close()
// Verify that the response status code is as expected.
if httpResponse.StatusCode != expectedStatus {
return &unexpectedResponseStatusError{httpResponse.StatusCode}
}
// Decode the response body. We allow unknown fields to ensure that we're
// forward-compatible with extended API responses.
decoder := json.NewDecoder(httpResponse.Body)
if err := decoder.Decode(response); err != nil {
return fmt.Errorf("unable to decode response body: %w", err)
}
// Success.
return nil
}
// TunnelCreate creates a new tunnel using the underlying API key. It returns
// the tunnel identifier, host token, and client token.
func TunnelCreate(ctx context.Context) (string, string, string, error) {
// Read the API token.
apiToken, err := readAPIToken()
if err != nil {
return "", "", "", fmt.Errorf("unable to read API token: %w", err)
}
// Create the request.
request := &tunnelCreateRequest{}
// Perform the operation and validate the response.
response := &tunnelCreateResponse{}
if err := callAPI(ctx, http.MethodPost, "tunnels", apiToken, request, response, http.StatusCreated); err != nil {
if unexpectedResponseStatusErr, ok := err.(*unexpectedResponseStatusError); ok {
if unexpectedResponseStatusErr.status == http.StatusUnauthorized {
return "", "", "", ErrUnauthorized
}
}
return "", "", "", err
} else if err = response.ensureValid(); err != nil {
return "", "", "", fmt.Errorf("received invalid response: %w", err)
}
// Success.
return response.ID, response.HostToken, response.ClientToken, nil
}
// TunnelHostExchange performs the host side of a tunnel offer exchange.
func TunnelHostExchange(ctx context.Context, tunnelID, hostToken, offer, signature string) (string, string, error) {
// Create the request.
request := &tunnelHostExchangeRequest{
Offer: offer,
Signature: signature,
}
// Perform the operation and validate the response.
response := &tunnelHostExchangeResponse{}
if err := callAPI(ctx, http.MethodPost, "tunnels/"+tunnelID, hostToken, request, response, http.StatusOK); err != nil {
if unexpectedResponseStatusErr, ok := err.(*unexpectedResponseStatusError); ok {
if unexpectedResponseStatusErr.status == http.StatusUnauthorized {
return "", "", ErrUnauthorized
}
}
return "", "", err
} else if err = response.ensureValid(); err != nil {
return "", "", fmt.Errorf("received invalid response: %w", err)
}
// Success.
return response.Offer, response.Signature, nil
}
// TunnelClientExchangeStart performs initiation of the client side of a tunnel
// offer exchange.
func TunnelClientExchangeStart(ctx context.Context, tunnelID, clientToken string) (string, string, string, error) {
// Create the request.
request := &tunnelClientExchangeStartRequest{}
// Perform the operation and validate the response.
response := &tunnelClientExchangeStartResponse{}
if err := callAPI(ctx, http.MethodGet, "tunnels/"+tunnelID, clientToken, request, response, http.StatusOK); err != nil {
if unexpectedResponseStatusErr, ok := err.(*unexpectedResponseStatusError); ok {
if unexpectedResponseStatusErr.status == http.StatusUnauthorized {
return "", "", "", ErrUnauthorized
}
}
return "", "", "", err
} else if err = response.ensureValid(); err != nil {
return "", "", "", fmt.Errorf("received invalid response: %w", err)
}
// Success.
return response.ExchangeID, response.Offer, response.Signature, nil
}
// TunnelClientExchangeFinish performs completion of the client side of a tunnel
// offer exchange.
func TunnelClientExchangeFinish(ctx context.Context, tunnelID, clientToken, exchangeID, offer, signature string) error {
// Create the request.
request := &tunnelClientExchangeFinishRequest{
ExchangeID: exchangeID,
Offer: offer,
Signature: signature,
}
// Perform the operation and validate the response.
response := &tunnelClientExchangeFinishResponse{}
if err := callAPI(ctx, http.MethodPut, "tunnels/"+tunnelID, clientToken, request, response, http.StatusOK); err != nil {
if unexpectedResponseStatusErr, ok := err.(*unexpectedResponseStatusError); ok {
if unexpectedResponseStatusErr.status == http.StatusUnauthorized {
return ErrUnauthorized
}
}
return err
} else if err = response.ensureValid(); err != nil {
return fmt.Errorf("received invalid response: %w", err)
}
// Success.
return nil
}