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
|
package client
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"time"
"github.com/dgrijalva/jwt-go"
"gitlab.com/gitlab-org/gitlab-pages/internal/domain"
"gitlab.com/gitlab-org/gitlab-pages/internal/httptransport"
"gitlab.com/gitlab-org/gitlab-pages/internal/source/gitlab/api"
"gitlab.com/gitlab-org/gitlab-pages/metrics"
)
// ConnectionErrorMsg to be returned with `gc.Status` if Pages
// fails to connect to the internal GitLab API, times out
// or a 401 given that the credentials used are wrong
const ConnectionErrorMsg = "failed to connect to internal Pages API"
// ErrUnauthorizedAPI is returned when resolving a domain with the GitLab API
// returns a http.StatusUnauthorized. This is an edge case when `domain-config-source=auto`
// and there are multiple instances of GitLab Rails and GitLab Pages running.
// See https://gitlab.com/gitlab-org/gitlab-pages/-/issues/535 for more info
var ErrUnauthorizedAPI = errors.New("pages endpoint unauthorized")
// Client is a HTTP client to access Pages internal API
type Client struct {
secretKey []byte
baseURL *url.URL
httpClient *http.Client
jwtTokenExpiry time.Duration
}
// NewClient initializes and returns new Client baseUrl is
// appConfig.InternalGitLabServer secretKey is appConfig.GitLabAPISecretKey
func NewClient(baseURL string, secretKey []byte, connectionTimeout, jwtTokenExpiry time.Duration) (*Client, error) {
if len(baseURL) == 0 || len(secretKey) == 0 {
return nil, errors.New("GitLab API URL or API secret has not been provided")
}
parsedURL, err := url.Parse(baseURL)
if err != nil {
return nil, err
}
if connectionTimeout == 0 {
return nil, errors.New("GitLab HTTP client connection timeout has not been provided")
}
if jwtTokenExpiry == 0 {
return nil, errors.New("GitLab JWT token expiry has not been provided")
}
return &Client{
secretKey: secretKey,
baseURL: parsedURL,
httpClient: &http.Client{
Timeout: connectionTimeout,
Transport: httptransport.NewTransportWithMetrics(
"gitlab_internal_api",
metrics.DomainsSourceAPITraceDuration,
metrics.DomainsSourceAPICallDuration,
metrics.DomainsSourceAPIReqTotal,
httptransport.DefaultTTFBTimeout,
),
},
jwtTokenExpiry: jwtTokenExpiry,
}, nil
}
// NewFromConfig creates a new client from Config struct
func NewFromConfig(config Config) (*Client, error) {
return NewClient(config.InternalGitLabServerURL(), config.GitlabAPISecret(), config.GitlabClientConnectionTimeout(), config.GitlabJWTTokenExpiry())
}
// Resolve returns a VirtualDomain configuration wrapped into a Lookup for a
// given host. It implements api.Resolve type.
func (gc *Client) Resolve(ctx context.Context, host string) *api.Lookup {
lookup := gc.GetLookup(ctx, host)
return &lookup
}
// GetLookup returns a VirtualDomain configuration wrapped into a Lookup for a
// given host
func (gc *Client) GetLookup(ctx context.Context, host string) api.Lookup {
params := url.Values{}
params.Set("host", host)
resp, err := gc.get(ctx, "/api/v4/internal/pages", params)
if err != nil {
return api.Lookup{Name: host, Error: err}
}
if resp == nil {
return api.Lookup{Name: host, Error: domain.ErrDomainDoesNotExist}
}
// ensure that entire response body has been read and close it, to make it
// possible to reuse HTTP connection. In case of a JSON being invalid and
// larger than 512 bytes, the response body will not be closed properly, thus
// we need to close it manually in every case.
defer func() {
io.Copy(ioutil.Discard, resp.Body)
resp.Body.Close()
}()
lookup := api.Lookup{Name: host}
lookup.Error = json.NewDecoder(resp.Body).Decode(&lookup.Domain)
return lookup
}
// Status checks that Pages can reach the rails internal Pages API
// for source domain configuration.
// Timeout is the same as -gitlab-client-http-timeout
func (gc *Client) Status() error {
res, err := gc.get(context.Background(), "/api/v4/internal/pages/status", url.Values{})
if err != nil {
return fmt.Errorf("%s: %v", ConnectionErrorMsg, err)
}
if res != nil && res.Body != nil {
res.Body.Close()
}
return nil
}
func (gc *Client) get(ctx context.Context, path string, params url.Values) (*http.Response, error) {
endpoint, err := gc.endpoint(path, params)
if err != nil {
return nil, err
}
req, err := gc.request(ctx, "GET", endpoint)
if err != nil {
return nil, err
}
resp, err := gc.httpClient.Do(req)
if err != nil {
return nil, err
}
if resp == nil {
return nil, errors.New("unknown response")
}
// StatusOK means we should return the API response
if resp.StatusCode == http.StatusOK {
return resp, nil
}
// nolint: errcheck
// best effort to discard and close the response body
io.Copy(ioutil.Discard, resp.Body)
resp.Body.Close()
// StatusNoContent means that a domain does not exist, it is not an error
if resp.StatusCode == http.StatusNoContent {
return nil, nil
} else if resp.StatusCode == http.StatusUnauthorized {
return nil, ErrUnauthorizedAPI
}
return nil, fmt.Errorf("HTTP status: %d", resp.StatusCode)
}
func (gc *Client) endpoint(path string, params url.Values) (*url.URL, error) {
endpoint, err := gc.baseURL.Parse(path)
if err != nil {
return nil, err
}
endpoint.RawQuery = params.Encode()
return endpoint, nil
}
func (gc *Client) request(ctx context.Context, method string, endpoint *url.URL) (*http.Request, error) {
req, err := http.NewRequest(method, endpoint.String(), nil)
if err != nil {
return nil, err
}
req = req.WithContext(ctx)
token, err := gc.token()
if err != nil {
return nil, err
}
req.Header.Set("Gitlab-Pages-Api-Request", token)
return req, nil
}
func (gc *Client) token() (string, error) {
claims := jwt.StandardClaims{
Issuer: "gitlab-pages",
ExpiresAt: time.Now().UTC().Add(gc.jwtTokenExpiry).Unix(),
}
token, err := jwt.NewWithClaims(jwt.SigningMethodHS256, claims).SignedString(gc.secretKey)
if err != nil {
return "", err
}
return token, nil
}
|