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
|
package acceptance_test
import (
"bytes"
"context"
"crypto/tls"
"crypto/x509"
"encoding/json"
"errors"
"fmt"
"io"
"io/fs"
"net"
"net/http"
"net/http/httptest"
"os"
"os/exec"
"path"
"strings"
"sync"
"testing"
"time"
"github.com/gorilla/mux"
"github.com/pires/go-proxyproto"
"github.com/stretchr/testify/require"
"golang.org/x/net/nettest"
"gitlab.com/gitlab-org/gitlab-pages/internal/request"
"gitlab.com/gitlab-org/gitlab-pages/internal/testhelpers"
"gitlab.com/gitlab-org/gitlab-pages/test/acceptance/testdata"
)
// The HTTPS certificate isn't signed by anyone. This http client is set up
// so it can talk to servers using it.
var (
// The HTTPS certificate isn't signed by anyone. This http client is set up
// so it can talk to servers using it.
TestHTTPSClient = &http.Client{
Transport: &http.Transport{
TLSClientConfig: &tls.Config{RootCAs: TestCertPool},
},
}
// Use HTTP with a very short timeout to repeatedly check for the server to be
// up. Again, ignore HTTP
QuickTimeoutHTTPSClient = &http.Client{
Transport: &http.Transport{
TLSClientConfig: &tls.Config{RootCAs: TestCertPool},
ResponseHeaderTimeout: 100 * time.Millisecond,
},
}
// Proxyv2 client
TestProxyv2Client = &http.Client{
Transport: &http.Transport{
DialContext: Proxyv2DialContext,
TLSClientConfig: &tls.Config{RootCAs: TestCertPool},
},
}
QuickTimeoutProxyv2Client = &http.Client{
Transport: &http.Transport{
DialContext: Proxyv2DialContext,
TLSClientConfig: &tls.Config{RootCAs: TestCertPool},
ResponseHeaderTimeout: 100 * time.Millisecond,
},
}
TestCertPool = x509.NewCertPool()
// Proxyv2 will create a dummy request with src 10.1.1.1:1000
// and dst 20.2.2.2:2000
Proxyv2DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) {
var d net.Dialer
conn, err := d.DialContext(ctx, network, addr)
if err != nil {
return nil, err
}
header := &proxyproto.Header{
Version: 2,
Command: proxyproto.PROXY,
TransportProtocol: proxyproto.TCPv4,
SourceAddress: net.ParseIP("10.1.1.1"),
SourcePort: 1000,
DestinationAddress: net.ParseIP("20.2.2.2"),
DestinationPort: 2000,
}
_, err = header.WriteTo(conn)
return conn, err
}
)
type tWriter struct {
t *testing.T
}
func (t *tWriter) Write(b []byte) (int, error) {
t.t.Log(string(bytes.TrimRight(b, "\r\n")))
return len(b), nil
}
type LogCaptureBuffer struct {
b bytes.Buffer
m sync.Mutex
}
func (b *LogCaptureBuffer) Read(p []byte) (n int, err error) {
b.m.Lock()
defer b.m.Unlock()
return b.b.Read(p)
}
func (b *LogCaptureBuffer) Write(p []byte) (n int, err error) {
b.m.Lock()
defer b.m.Unlock()
return b.b.Write(p)
}
func (b *LogCaptureBuffer) String() string {
b.m.Lock()
defer b.m.Unlock()
return b.b.String()
}
func (b *LogCaptureBuffer) Reset() {
b.m.Lock()
defer b.m.Unlock()
b.b.Reset()
}
// ListenSpec is used to point at a gitlab-pages http server, preserving the
// type of port it is (http, https, proxy)
type ListenSpec struct {
Type string
Host string
Port string
}
func supportedListeners() []ListenSpec {
if !nettest.SupportsIPv6() {
return ipv4Listeners
}
return listeners
}
func (l ListenSpec) URL(suffix string) string {
scheme := request.SchemeHTTP
if l.Type == request.SchemeHTTPS || l.Type == "https-proxyv2" {
scheme = request.SchemeHTTPS
}
suffix = strings.TrimPrefix(suffix, "/")
return fmt.Sprintf("%s://%s/%s", scheme, l.JoinHostPort(), suffix)
}
// Returns only once this spec points at a working TCP server
func (l ListenSpec) WaitUntilRequestSucceeds(done chan struct{}) error {
timeout := 5 * time.Second
for start := time.Now(); time.Since(start) < timeout; {
select {
case <-done:
return fmt.Errorf("server has shut down already")
default:
}
req, err := http.NewRequest("GET", l.URL("/"), nil)
if err != nil {
return err
}
client := QuickTimeoutHTTPSClient
if l.Type == "https-proxyv2" {
client = QuickTimeoutProxyv2Client
}
response, err := client.Transport.RoundTrip(req)
if err != nil {
time.Sleep(100 * time.Millisecond)
continue
}
response.Body.Close()
if code := response.StatusCode; code >= 200 && code < 500 {
return nil
}
time.Sleep(100 * time.Millisecond)
}
return fmt.Errorf("timed out after %v waiting for listener %v", timeout, l)
}
func (l ListenSpec) JoinHostPort() string {
return net.JoinHostPort(l.Host, l.Port)
}
func RunPagesProcess(t *testing.T, opts ...processOption) *LogCaptureBuffer {
chdir := false
chdirCleanup := testhelpers.ChdirInPath(t, "../../shared/pages", &chdir)
wd, err := os.Getwd()
require.NoError(t, err)
processCfg := defaultProcessConfig
for _, opt := range opts {
opt(&processCfg)
}
if processCfg.gitlabStubOpts.pagesRoot == "" {
processCfg.gitlabStubOpts.pagesRoot = wd
}
source := NewGitlabDomainsSourceStub(t, processCfg.gitlabStubOpts)
gitLabAPISecretKey := CreateGitLabAPISecretKeyFixtureFile(t)
processCfg.extraArgs = append(
processCfg.extraArgs,
"-pages-root", wd,
"-internal-gitlab-server", source.URL,
"-api-secret-key", gitLabAPISecretKey,
)
logBuf, cleanup := runPagesProcess(t, processCfg.wait, processCfg.pagesBinary, processCfg.listeners, "", processCfg.envs, processCfg.extraArgs...)
t.Cleanup(func() {
source.Close()
chdirCleanup()
cleanup()
})
return logBuf
}
func RunPagesProcessWithSSLCertFile(t *testing.T, listeners []ListenSpec, sslCertFile string) {
RunPagesProcess(t,
withListeners(listeners),
withArguments([]string{
"-config=" + defaultAuthConfig(t),
}),
withEnv([]string{"SSL_CERT_FILE=" + sslCertFile}),
)
}
func RunPagesProcessWithSSLCertDir(t *testing.T, listeners []ListenSpec, sslCertFile string) {
// Create temporary cert dir
sslCertDir := t.TempDir()
// Copy sslCertFile into temp cert dir
err := copyFile(sslCertDir+"/"+path.Base(sslCertFile), sslCertFile)
require.NoError(t, err)
RunPagesProcess(t,
withListeners(listeners),
withArguments([]string{
"-config=" + defaultAuthConfig(t),
}),
withEnv([]string{"SSL_CERT_DIR=" + sslCertDir}),
)
}
func runPagesProcess(t *testing.T, wait bool, pagesBinary string, listeners []ListenSpec, promPort string, extraEnv []string, extraArgs ...string) (*LogCaptureBuffer, func()) {
t.Helper()
_, err := os.Stat(pagesBinary)
require.NoError(t, err)
logBuf := &LogCaptureBuffer{}
out := io.MultiWriter(&tWriter{t}, logBuf)
args := getPagesArgs(t, listeners, promPort, extraArgs)
cmd := exec.Command(pagesBinary, args...)
cmd.Env = append(os.Environ(), extraEnv...)
cmd.Stdout = out
cmd.Stderr = out
require.NoError(t, cmd.Start())
t.Logf("Running %s %v", pagesBinary, args)
waitCh := make(chan struct{})
go func() {
require.NoError(t, cmd.Wait())
close(waitCh)
}()
cleanup := func() {
require.NoError(t, cmd.Process.Signal(os.Interrupt))
<-waitCh
}
if wait {
for _, spec := range listeners {
if err := spec.WaitUntilRequestSucceeds(waitCh); err != nil {
cleanup()
t.Fatal(err)
}
}
}
return logBuf, cleanup
}
func getPagesArgs(t *testing.T, listeners []ListenSpec, promPort string, extraArgs []string) (args []string) {
var hasHTTPS bool
args = append(args, "-log-verbose=true")
for _, spec := range listeners {
args = append(args, "-listen-"+spec.Type, spec.JoinHostPort())
if strings.Contains(spec.Type, request.SchemeHTTPS) {
hasHTTPS = true
}
}
if hasHTTPS {
key, cert := CreateHTTPSFixtureFiles(t)
args = append(args, "-root-key", key, "-root-cert", cert)
}
if !contains(extraArgs, "-pages-root") {
args = append(args, "-pages-root", "../../shared/pages")
}
// default resolver configuration to execute tests faster
if !contains(extraArgs, "-gitlab-retrieval-") {
args = append(args, "-gitlab-retrieval-timeout", "50ms",
"-gitlab-retrieval-interval", "10ms",
"-gitlab-retrieval-retries", "1")
}
if promPort != "" {
args = append(args, "-metrics-address", promPort)
}
args = append(args, extraArgs...)
return
}
func contains(slice []string, s string) bool {
for _, e := range slice {
if strings.Contains(e, s) {
return true
}
}
return false
}
// Does a HTTP(S) GET against the listener specified, setting a fake
// Host: and constructing the URL from the listener and the URL suffix.
func GetPageFromListener(t *testing.T, spec ListenSpec, host, urlsuffix string) (*http.Response, error) {
return GetPageFromListenerWithHeaders(t, spec, host, urlsuffix, http.Header{})
}
func GetPageFromListenerWithHeaders(t *testing.T, spec ListenSpec, host, urlSuffix string, header http.Header) (*http.Response, error) {
t.Helper()
url := spec.URL(urlSuffix)
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, err
}
req.Host = host
req.Header = header
return DoPagesRequest(t, spec, req)
}
func DoPagesRequest(t *testing.T, spec ListenSpec, req *http.Request) (*http.Response, error) {
t.Logf("curl -X %s -H'Host: %s' %s", req.Method, req.Host, req.URL)
if spec.Type == "https-proxyv2" {
return TestProxyv2Client.Do(req)
}
return TestHTTPSClient.Do(req)
}
func GetRedirectPage(t *testing.T, spec ListenSpec, host, urlsuffix string) (*http.Response, error) {
return GetRedirectPageWithCookie(t, spec, host, urlsuffix, "")
}
func GetProxyRedirectPageWithCookie(t *testing.T, spec ListenSpec, host string, urlsuffix string, cookie string, https bool) (*http.Response, error) {
schema := request.SchemeHTTP
if https {
schema = request.SchemeHTTPS
}
header := http.Header{
"X-Forwarded-Proto": []string{schema},
"X-Forwarded-Host": []string{host},
"cookie": []string{cookie},
}
return GetRedirectPageWithHeaders(t, spec, host, urlsuffix, header)
}
func GetRedirectPageWithCookie(t *testing.T, spec ListenSpec, host, urlsuffix string, cookie string) (*http.Response, error) {
return GetRedirectPageWithHeaders(t, spec, host, urlsuffix, http.Header{"cookie": []string{cookie}})
}
func GetRedirectPageWithHeaders(t *testing.T, spec ListenSpec, host, urlsuffix string, header http.Header) (*http.Response, error) {
url := spec.URL(urlsuffix)
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, err
}
req.Header = header
req.Host = host
if spec.Type == "https-proxyv2" {
return TestProxyv2Client.Transport.RoundTrip(req)
}
return TestHTTPSClient.Transport.RoundTrip(req)
}
func ClientWithConfig(tlsConfig *tls.Config) (*http.Client, func()) {
tlsConfig.RootCAs = TestCertPool
tr := &http.Transport{TLSClientConfig: tlsConfig}
client := &http.Client{Transport: tr}
return client, tr.CloseIdleConnections
}
type stubOpts struct {
m sync.RWMutex
apiCalled bool
authHandler http.HandlerFunc
userHandler http.HandlerFunc
pagesHandler http.HandlerFunc
pagesStatusResponse int
pagesRoot string
delay time.Duration
}
func NewGitlabDomainsSourceStub(t *testing.T, opts *stubOpts) *httptest.Server {
t.Helper()
require.NotNil(t, opts)
router := mux.NewRouter()
pagesHandler := defaultAPIHandler(t, opts)
if opts.pagesHandler != nil {
pagesHandler = opts.pagesHandler
}
router.HandleFunc("/api/v4/internal/pages", pagesHandler)
authHandler := defaultAuthHandler(t)
if opts.authHandler != nil {
authHandler = opts.authHandler
}
router.HandleFunc("/oauth/token", authHandler)
userHandler := defaultUserHandler(t)
if opts.userHandler != nil {
userHandler = opts.userHandler
}
router.HandleFunc("/api/v4/user", userHandler)
router.HandleFunc("/api/v4/projects/{project_id:[0-9]+}/pages_access", func(w http.ResponseWriter, r *http.Request) {
if handleAccessControlArtifactRequests(t, w, r) {
return
}
handleAccessControlRequests(t, w, r)
})
return httptest.NewServer(router)
}
func (o *stubOpts) setAPICalled(v bool) {
o.m.Lock()
defer o.m.Unlock()
o.apiCalled = v
}
func (o *stubOpts) getAPICalled() bool {
o.m.RLock()
defer o.m.RUnlock()
return o.apiCalled
}
func lookupFromFile(t *testing.T, domain string, w http.ResponseWriter) {
fixture, err := os.Open("../../shared/lookups/" + domain + ".json")
if errors.Is(err, fs.ErrNotExist) {
w.WriteHeader(http.StatusNoContent)
t.Logf("GitLab domain %s source stub served 204", domain)
return
}
defer fixture.Close()
require.NoError(t, err)
_, err = io.Copy(w, fixture)
require.NoError(t, err)
t.Logf("GitLab domain %s source stub served lookup", domain)
}
func defaultAPIHandler(t *testing.T, opts *stubOpts) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
domain := r.URL.Query().Get("host")
if domain == "127.0.0.1" {
// shortcut for healthy checkup done by WaitUntilRequestSucceeds
w.WriteHeader(http.StatusNoContent)
return
}
// to test slow responses from the API
if opts.delay > 0 {
time.Sleep(opts.delay)
}
opts.setAPICalled(true)
if opts.pagesStatusResponse != 0 {
w.WriteHeader(opts.pagesStatusResponse)
return
}
// check if predefined response exists
if responseFn, ok := testdata.DomainResponses[domain]; ok {
err := json.NewEncoder(w).Encode(responseFn(t, opts.pagesRoot))
require.NoError(t, err)
return
}
// serve lookup from files
lookupFromFile(t, domain, w)
}
}
func defaultAuthHandler(t *testing.T) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
require.Equal(t, "POST", r.Method)
err := json.NewEncoder(w).Encode(struct {
AccessToken string `json:"access_token"`
}{
AccessToken: "abc",
})
require.NoError(t, err)
}
}
func defaultUserHandler(t *testing.T) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
require.Equal(t, "Bearer abc", r.Header.Get("Authorization"))
w.WriteHeader(http.StatusOK)
}
}
func newConfigFile(t *testing.T, configs ...string) string {
t.Helper()
f, err := os.CreateTemp(t.TempDir(), "gitlab-pages-config")
require.NoError(t, err)
defer f.Close()
for _, config := range configs {
_, err := fmt.Fprintf(f, "%s\n", config)
require.NoError(t, err)
}
return f.Name()
}
func defaultConfigFileWith(t *testing.T, configs ...string) string {
t.Helper()
configs = append(configs, "auth-client-id=clientID",
"auth-client-secret=clientSecret",
"auth-secret=authSecret",
"auth-scope=authScope",
)
name := newConfigFile(t, configs...)
return name
}
func copyFile(dest, src string) error {
srcFile, err := os.Open(src)
if err != nil {
return err
}
defer srcFile.Close()
srcInfo, err := srcFile.Stat()
if err != nil {
return err
}
destFile, err := os.OpenFile(dest, os.O_WRONLY|os.O_CREATE|os.O_EXCL, srcInfo.Mode())
if err != nil {
return err
}
defer destFile.Close()
_, err = io.Copy(destFile, srcFile)
return err
}
func setupTransport(t *testing.T) {
t.Helper()
transport := (TestHTTPSClient.Transport).(*http.Transport)
defer func(t time.Duration) {
transport.ResponseHeaderTimeout = t
}(transport.ResponseHeaderTimeout)
transport.ResponseHeaderTimeout = 5 * time.Second
}
|