-
Notifications
You must be signed in to change notification settings - Fork 0
/
http.go
258 lines (227 loc) · 6.76 KB
/
http.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
package gerrittest
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"strings"
"time"
"github.com/andygrunwald/go-gerrit"
"github.com/opalmer/dockertest"
log "github.com/sirupsen/logrus"
"golang.org/x/crypto/ssh"
)
// getResponseBody returns the body of the given response as bytes with the
// magic prefix removed.
func getResponseBody(response *http.Response) ([]byte, error) {
body, err := ioutil.ReadAll(response.Body)
if err != nil {
return nil, err
}
return gerrit.RemoveMagicPrefixLine(body), response.Body.Close()
}
// HTTPClient is a simple client for talking to Gerrit within a
// container. This is not intended as a replacement for go-gerrit.
// Instead, it's intended to get validate that Gerrit is setup
// correctly and then perform the final steps to get it ready for
// testing.
type HTTPClient struct {
client *http.Client
config *Config
Prefix string
}
// url concatenates the prefix and the given tai.
func (h *HTTPClient) url(tail string) string {
return h.Prefix + tail
}
// newRequest constructs a new http.Request, sets the proper headers and then
// logs the request.
func (h *HTTPClient) newRequest(method string, tail string, body []byte) (*http.Request, error) {
requestURL := h.url(tail)
var bodyReader io.Reader
if body != nil {
bodyReader = bytes.NewReader(body)
}
request, err := http.NewRequest(method, requestURL, bodyReader)
if err != nil {
return nil, err
}
request.Header.Set("Content-Type", "application/json")
if h.config.Username != "" && h.config.Password != "" {
request.SetBasicAuth(h.config.Username, h.config.Password)
}
// If the url is not prefixed with /a/ then assume we're relying
// on X-User to tell Gerrit to trust our request. In all other cases
// the cookie Gerrit gives us back will be relies
if !strings.HasPrefix(tail, "/a/") {
request.Header.Add("X-User", h.config.Username)
}
for _, cookie := range h.client.Jar.Cookies(&url.URL{Host: "localhost"}) {
request.AddCookie(cookie)
if cookie.Name == "XSRF_TOKEN" {
request.Header.Set("X-Gerrit-Auth", cookie.Value)
}
}
log.WithFields(log.Fields{
"action": "request",
"method": method,
"url": requestURL,
"body": string(body),
}).Debug()
return request, nil
}
// do performs the request using the internal http client.
func (h *HTTPClient) do(request *http.Request, expectedCode int) (*http.Response, []byte, error) {
logger := log.WithFields(log.Fields{
"action": "response",
"method": request.Method,
"url": request.URL,
})
if expectedCode != 0 {
logger = logger.WithField("status-expected", expectedCode)
}
start := time.Now()
response, err := h.client.Do(request)
if err != nil {
logger.WithError(err).Error()
return response, nil, err
}
body, err := getResponseBody(response)
if err != nil {
return nil, nil, err
}
logger = logger.WithFields(log.Fields{
"duration": time.Since(start),
"status": response.StatusCode,
})
if expectedCode == 0 {
expectedCode = response.StatusCode
}
if response.StatusCode != expectedCode {
logger.WithField("body", strings.TrimSpace(string(body))).Warn()
return response, body, fmt.Errorf(
"response code %d != %d", response.StatusCode, expectedCode)
}
logger.Debug()
return response, body, err
}
// login will attempt to hit /login/ as the given user.
func (h *HTTPClient) login() error {
request, err := h.newRequest(http.MethodGet, "/login/", nil)
if err != nil {
return err
}
_, _, err = h.do(request, http.StatusOK)
return err
}
// Gerrit will return a *gerrit.Gerrit client. Note, the username
// and password must already be set and basic validation to ensure
// the client is setup properly is performed.
func (h *HTTPClient) Gerrit() (*gerrit.Client, error) {
if h.config.Username == "" || h.config.Password == "" {
return nil, errors.New("username and password required")
}
parsed, err := url.Parse(h.Prefix)
if err != nil {
return nil, err
}
client, err := gerrit.NewClient(fmt.Sprintf(
"%s://%s:%s@%s", parsed.Scheme, h.config.Username, h.config.Password,
parsed.Host), nil)
if err != nil {
return nil, err
}
if _, _, err := client.Accounts.GetAccount("self"); err != nil {
return nil, err
}
return client, nil
}
// generatePassword generates and returns the account password. Note, this
// only works for the current account (the one which set the cookie
// in GetAccount())
func (h *HTTPClient) generatePassword() (string, error) {
body, err := json.Marshal(&gerrit.HTTPPasswordInput{Generate: true})
if err != nil {
return "", err
}
request, err := h.newRequest(http.MethodPut, "/a/accounts/self/password.http", body)
if err != nil {
return "", err
}
_, responseBody, err := h.do(request, http.StatusOK)
if err != nil {
return "", err
}
// The generated password includes quotes, the below code removes
// those quotes.
output := strings.TrimSpace(string(responseBody))
if len(output) == 0 {
return "", nil
}
return output[1 : len(output)-1], nil
}
// setPassword sets the http password to the given value.
func (h *HTTPClient) setPassword(password string) error {
body, err := json.Marshal(&gerrit.HTTPPasswordInput{HTTPPassword: password})
if err != nil {
return err
}
request, err := h.newRequest(
http.MethodPut, "/a/accounts/self/password.http", body)
if err != nil {
return err
}
_, _, err = h.do(request, http.StatusOK)
return err
}
// insertPublicKeys will insert all public keys in the config into Gerrit.
func (h *HTTPClient) insertPublicKeys() error {
logger := log.WithField("phase", "insert-public-key")
for _, key := range h.config.SSHKeys {
logger.WithField("key", key).Debug()
request, err := h.newRequest(
http.MethodPost, "/a/accounts/self/sshkeys",
bytes.TrimSpace(ssh.MarshalAuthorizedKey(key.Public)))
if err != nil {
return err
}
request.Header.Set("Content-Type", "plain/text")
_, _, err = h.do(request, http.StatusCreated)
if err != nil {
return err
}
}
return nil
}
func (h *HTTPClient) configureEmail() error {
g, err := h.Gerrit()
if err != nil {
return err
}
account, _, err := g.Accounts.GetAccount("self")
if err != nil {
return err
}
_, _, err = g.Accounts.CreateAccountEmail(account.Username, h.config.GitConfig["user.email"], &gerrit.EmailInput{
Email: h.config.GitConfig["user.email"],
Preferred: true,
NoConfirmation: true,
})
return err
}
// NewHTTPClient takes a *Service struct and returns an *HTTPClient. No
// validation to ensure the service is actually running is performed.
func NewHTTPClient(config *Config, port *dockertest.Port) (*HTTPClient, error) {
if config.Username == "" {
return nil, errors.New("username not provided")
}
return &HTTPClient{
config: config,
client: &http.Client{Jar: NewCookieJar()},
Prefix: fmt.Sprintf("http://%s:%d", port.Address, port.Public),
}, nil
}