File: testutilserve.go

package info (click to toggle)
docker-buildx 0.19.3%2Bds1-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 2,852 kB
  • sloc: sh: 318; makefile: 73
file content (98 lines) | stat: -rw-r--r-- 1,965 bytes parent folder | download
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
package gitutil

import (
	"context"
	"fmt"
	"net"
	"net/http"
	"testing"

	"github.com/pkg/errors"
	"github.com/stretchr/testify/require"
)

type gitServe struct {
	token string
}

type GitServeOpt func(*gitServe)

func WithAccessToken(token string) GitServeOpt {
	return func(s *gitServe) {
		s.token = token
	}
}

func GitServeHTTP(c *Git, t testing.TB, opts ...GitServeOpt) (url string) {
	t.Helper()
	gitUpdateServerInfo(c, t)
	ctx, cancel := context.WithCancelCause(context.TODO())

	gs := &gitServe{}
	for _, opt := range opts {
		opt(gs)
	}

	ready := make(chan struct{})
	done := make(chan struct{})

	name := "test.git"
	dir, err := c.GitDir()
	if err != nil {
		cancel(err)
	}

	var addr string
	go func() {
		mux := http.NewServeMux()
		prefix := fmt.Sprintf("/%s/", name)

		handler := func(next http.Handler) http.Handler {
			var tokenChecked bool
			return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
				if gs.token != "" && !tokenChecked {
					t.Logf("git access token to check: %q", gs.token)
					user, pass, _ := r.BasicAuth()
					t.Logf("basic auth: user=%q pass=%q", user, pass)
					if pass != gs.token {
						http.Error(w, "Unauthorized", http.StatusUnauthorized)
						return
					}
					tokenChecked = true
				}
				next.ServeHTTP(w, r)
			})
		}

		mux.Handle(prefix, handler(http.StripPrefix(prefix, http.FileServer(http.Dir(dir)))))
		l, err := net.Listen("tcp", "localhost:0")
		if err != nil {
			panic(err)
		}

		addr = l.Addr().String()

		close(ready)

		s := http.Server{Handler: mux} //nolint:gosec // potential attacks are not relevant for tests
		go s.Serve(l)
		<-ctx.Done()
		s.Shutdown(context.TODO())
		l.Close()

		close(done)
	}()
	<-ready

	t.Cleanup(func() {
		cancel(errors.Errorf("cleanup"))
		<-done
	})
	return fmt.Sprintf("http://%s/%s", addr, name)
}

func gitUpdateServerInfo(c *Git, tb testing.TB) {
	tb.Helper()
	_, err := fakeGit(c, "update-server-info")
	require.NoError(tb, err)
}