Skip to content

Commit 3ca05e1

Browse files
authored
Merge pull request #524 from racdev/libgit2-proxy-support
2 parents be57586 + 3d276b6 commit 3ca05e1

File tree

4 files changed

+300
-1
lines changed

4 files changed

+300
-1
lines changed

go.mod

+1
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ require (
99
github.com/Masterminds/semver/v3 v3.1.1
1010
github.com/ProtonMail/go-crypto v0.0.0-20210428141323-04723f9f07d7
1111
github.com/cyphar/filepath-securejoin v0.2.2
12+
github.com/elazarl/goproxy v0.0.0-20211114080932-d06c3be7c11b
1213
github.com/fluxcd/pkg/apis/meta v0.10.2
1314
github.com/fluxcd/pkg/gittestserver v0.5.0
1415
github.com/fluxcd/pkg/gitutil v0.1.0

go.sum

+5-1
Original file line numberDiff line numberDiff line change
@@ -267,8 +267,11 @@ github.com/docopt/docopt-go v0.0.0-20180111231733-ee0de3bc6815/go.mod h1:WwZ+bS3
267267
github.com/dustin/go-humanize v0.0.0-20171111073723-bb3d318650d4/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk=
268268
github.com/dustin/go-humanize v1.0.0 h1:VSnTsYCnlFHaM2/igO1h6X3HA71jcobQuxemgkq4zYo=
269269
github.com/dustin/go-humanize v1.0.0/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk=
270-
github.com/elazarl/goproxy v0.0.0-20180725130230-947c36da3153 h1:yUdfgN0XgIJw7foRItutHYUIhlcKzcSf5vDpdhQAKTc=
271270
github.com/elazarl/goproxy v0.0.0-20180725130230-947c36da3153/go.mod h1:/Zj4wYkgs4iZTTu3o/KG3Itv/qCCa8VVMlb3i9OVuzc=
271+
github.com/elazarl/goproxy v0.0.0-20211114080932-d06c3be7c11b h1:1XqENn2YoYZd6w3Awx+7oa+aR87DFIZJFLF2n1IojA0=
272+
github.com/elazarl/goproxy v0.0.0-20211114080932-d06c3be7c11b/go.mod h1:Ro8st/ElPeALwNFlcTpWmkr6IoMFfkjXAvTHpevnDsM=
273+
github.com/elazarl/goproxy/ext v0.0.0-20190711103511-473e67f1d7d2 h1:dWB6v3RcOy03t/bUadywsbyrQwCqZeNIEX6M1OtSZOM=
274+
github.com/elazarl/goproxy/ext v0.0.0-20190711103511-473e67f1d7d2/go.mod h1:gNh8nYJoAm43RfaxurUnxr+N1PwuFV3ZMl/efxlIlY8=
272275
github.com/emicklei/go-restful v0.0.0-20170410110728-ff4f55a20633/go.mod h1:otzb+WCGbkyDHkqmQmT5YD2WR4BBwUdeQoFo8l/7tVs=
273276
github.com/emicklei/go-restful v2.9.5+incompatible/go.mod h1:otzb+WCGbkyDHkqmQmT5YD2WR4BBwUdeQoFo8l/7tVs=
274277
github.com/emirpasic/gods v1.12.0 h1:QAUIPSaCu4G+POclxeqb3F+WPpdKqFGlw36+yOzGlrg=
@@ -806,6 +809,7 @@ github.com/prometheus/procfs v0.6.0/go.mod h1:cz+aTbrPOrUb4q7XlbU9ygM+/jj0fzG6c1
806809
github.com/prometheus/tsdb v0.7.1/go.mod h1:qhTCs0VvXwvX/y3TZrWD7rabWM+ijKTux40TwIPHuXU=
807810
github.com/rogpeppe/fastuuid v0.0.0-20150106093220-6724a57986af/go.mod h1:XWv6SoW27p1b0cqNHllgS5HIMJraePCO15w5zCzIWYg=
808811
github.com/rogpeppe/fastuuid v1.2.0/go.mod h1:jVj6XXZzXRy/MSR5jhDC/2q6DgLz+nrA6LYCDYWNEvQ=
812+
github.com/rogpeppe/go-charset v0.0.0-20180617210344-2471d30d28b4/go.mod h1:qgYeAmZ5ZIpBWTGllZSQnw97Dj+woV0toclVaRGI8pc=
809813
github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4=
810814
github.com/rogpeppe/go-internal v1.5.2/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc=
811815
github.com/rs/xid v1.2.1 h1:mhH9Nq+C1fY2l1XIpgxIiUOfNpRBYH1kKcr+qfKgjRc=

pkg/git/libgit2/checkout.go

+4
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,7 @@ func (c *CheckoutBranch) Checkout(ctx context.Context, path, url string, opts *g
6464
FetchOptions: &git2go.FetchOptions{
6565
DownloadTags: git2go.DownloadTagsNone,
6666
RemoteCallbacks: RemoteCallbacks(ctx, opts),
67+
ProxyOptions: git2go.ProxyOptions{Type: git2go.ProxyTypeAuto},
6768
},
6869
CheckoutBranch: c.Branch,
6970
})
@@ -93,6 +94,7 @@ func (c *CheckoutTag) Checkout(ctx context.Context, path, url string, opts *git.
9394
FetchOptions: &git2go.FetchOptions{
9495
DownloadTags: git2go.DownloadTagsAll,
9596
RemoteCallbacks: RemoteCallbacks(ctx, opts),
97+
ProxyOptions: git2go.ProxyOptions{Type: git2go.ProxyTypeAuto},
9698
},
9799
})
98100
if err != nil {
@@ -116,6 +118,7 @@ func (c *CheckoutCommit) Checkout(ctx context.Context, path, url string, opts *g
116118
FetchOptions: &git2go.FetchOptions{
117119
DownloadTags: git2go.DownloadTagsNone,
118120
RemoteCallbacks: RemoteCallbacks(ctx, opts),
121+
ProxyOptions: git2go.ProxyOptions{Type: git2go.ProxyTypeAuto},
119122
},
120123
})
121124
if err != nil {
@@ -147,6 +150,7 @@ func (c *CheckoutSemVer) Checkout(ctx context.Context, path, url string, opts *g
147150
FetchOptions: &git2go.FetchOptions{
148151
DownloadTags: git2go.DownloadTagsAll,
149152
RemoteCallbacks: RemoteCallbacks(ctx, opts),
153+
ProxyOptions: git2go.ProxyOptions{Type: git2go.ProxyTypeAuto},
150154
},
151155
})
152156
if err != nil {
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,290 @@
1+
/*
2+
Copyright 2021 The Flux authors
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
http://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
*/
16+
17+
package proxy
18+
19+
import (
20+
"context"
21+
"fmt"
22+
"net"
23+
"net/http"
24+
"net/url"
25+
"os"
26+
"strings"
27+
"testing"
28+
"time"
29+
30+
"github.com/elazarl/goproxy"
31+
"github.com/fluxcd/pkg/gittestserver"
32+
. "github.com/onsi/gomega"
33+
34+
"github.com/fluxcd/source-controller/pkg/git"
35+
"github.com/fluxcd/source-controller/pkg/git/gogit"
36+
"github.com/fluxcd/source-controller/pkg/git/libgit2"
37+
"github.com/fluxcd/source-controller/pkg/git/strategy"
38+
)
39+
40+
// These tests are run in a different _test.go file because go-git uses the ProxyFromEnvironment function of the net/http package
41+
// which caches the Proxy settings, hence not including other tests in the same file ensures a clean proxy setup for the tests to run.
42+
func TestCheckoutStrategyForImplementation_Proxied(t *testing.T) {
43+
44+
type cleanupFunc func()
45+
46+
type testCase struct {
47+
name string
48+
gitImpl git.Implementation
49+
url string
50+
branch string
51+
setupGitProxy func(g *WithT, proxy *goproxy.ProxyHttpServer, proxyGotRequest *bool) (*git.AuthOptions, cleanupFunc)
52+
shortTimeout bool
53+
wantUsedProxy bool
54+
wantError bool
55+
}
56+
57+
g := NewWithT(t)
58+
59+
// Get a free port for proxy to use.
60+
l, err := net.Listen("tcp", ":0")
61+
g.Expect(err).ToNot(HaveOccurred())
62+
proxyAddr := fmt.Sprintf("localhost:%d", l.Addr().(*net.TCPAddr).Port)
63+
g.Expect(l.Close()).ToNot(HaveOccurred())
64+
65+
// Note there is no libgit2 HTTP_PROXY test as libgit2 doesnt support proxied HTTP requests.
66+
cases := []testCase{
67+
{
68+
name: "libgit2_HTTPS_PROXY",
69+
gitImpl: libgit2.Implementation,
70+
url: "https://example.com/bar/test-reponame",
71+
branch: "main",
72+
setupGitProxy: func(g *WithT, proxy *goproxy.ProxyHttpServer, proxyGotRequest *bool) (*git.AuthOptions, cleanupFunc) {
73+
// Create the git server.
74+
gitServer, err := gittestserver.NewTempGitServer()
75+
g.Expect(err).ToNot(HaveOccurred())
76+
77+
username := "test-user"
78+
password := "test-password"
79+
gitServer.Auth(username, password)
80+
gitServer.KeyDir(gitServer.Root())
81+
82+
// Start the HTTPS server.
83+
examplePublicKey, err := os.ReadFile("../testdata/certs/server.pem")
84+
g.Expect(err).ToNot(HaveOccurred())
85+
examplePrivateKey, err := os.ReadFile("../testdata/certs/server-key.pem")
86+
g.Expect(err).ToNot(HaveOccurred())
87+
exampleCA, err := os.ReadFile("../testdata/certs/ca.pem")
88+
g.Expect(err).ToNot(HaveOccurred())
89+
err = gitServer.StartHTTPS(examplePublicKey, examplePrivateKey, exampleCA, "example.com")
90+
g.Expect(err).ToNot(HaveOccurred())
91+
92+
// Initialize a git repo.
93+
repoPath := "bar/test-reponame"
94+
err = gitServer.InitRepo("../testdata/repo1", "main", repoPath)
95+
g.Expect(err).ToNot(HaveOccurred())
96+
97+
u, err := url.Parse(gitServer.HTTPAddress())
98+
g.Expect(err).ToNot(HaveOccurred())
99+
100+
// The request is being forwarded to the local test git server in this handler.
101+
// The certificate used here is valid for both example.com and localhost.
102+
var proxyHandler goproxy.FuncHttpsHandler = func(host string, ctx *goproxy.ProxyCtx) (*goproxy.ConnectAction, string) {
103+
// Check if the host matches with the git server address and the user-agent is the expected git client.
104+
userAgent := ctx.Req.Header.Get("User-Agent")
105+
if strings.Contains(host, "example.com") && strings.Contains(userAgent, "libgit2") {
106+
*proxyGotRequest = true
107+
return goproxy.OkConnect, u.Host
108+
}
109+
// Reject if it isn't our request.
110+
return goproxy.RejectConnect, host
111+
}
112+
proxy.OnRequest().HandleConnect(proxyHandler)
113+
114+
return &git.AuthOptions{
115+
Transport: git.HTTPS,
116+
Username: username,
117+
Password: password,
118+
CAFile: exampleCA,
119+
}, func() {
120+
os.RemoveAll(gitServer.Root())
121+
gitServer.StopHTTP()
122+
}
123+
},
124+
shortTimeout: false,
125+
wantUsedProxy: true,
126+
wantError: false,
127+
},
128+
{
129+
name: "gogit_HTTP_PROXY",
130+
gitImpl: gogit.Implementation,
131+
url: "http://example.com/bar/test-reponame",
132+
branch: "main",
133+
setupGitProxy: func(g *WithT, proxy *goproxy.ProxyHttpServer, proxyGotRequest *bool) (*git.AuthOptions, cleanupFunc) {
134+
// Create the git server.
135+
gitServer, err := gittestserver.NewTempGitServer()
136+
g.Expect(err).ToNot(HaveOccurred())
137+
138+
username := "test-user"
139+
password := "test-password"
140+
gitServer.Auth(username, password)
141+
gitServer.KeyDir(gitServer.Root())
142+
143+
g.Expect(gitServer.StartHTTP()).ToNot(HaveOccurred())
144+
145+
// Initialize a git repo.
146+
err = gitServer.InitRepo("../testdata/repo1", "main", "bar/test-reponame")
147+
g.Expect(err).ToNot(HaveOccurred())
148+
149+
u, err := url.Parse(gitServer.HTTPAddress())
150+
g.Expect(err).ToNot(HaveOccurred())
151+
152+
// The request is being forwarded to the local test git server in this handler.
153+
var proxyHandler goproxy.FuncReqHandler = func(req *http.Request, ctx *goproxy.ProxyCtx) (*http.Request, *http.Response) {
154+
userAgent := req.Header.Get("User-Agent")
155+
if strings.Contains(req.Host, "example.com") && strings.Contains(userAgent, "git") {
156+
*proxyGotRequest = true
157+
req.Host = u.Host
158+
req.URL.Host = req.Host
159+
return req, nil
160+
}
161+
// Reject if it isnt our request.
162+
return req, goproxy.NewResponse(req, goproxy.ContentTypeText, http.StatusForbidden, "")
163+
}
164+
proxy.OnRequest().Do(proxyHandler)
165+
166+
return &git.AuthOptions{
167+
Transport: git.HTTP,
168+
Username: username,
169+
Password: password,
170+
}, func() {
171+
os.RemoveAll(gitServer.Root())
172+
gitServer.StopHTTP()
173+
}
174+
},
175+
shortTimeout: false,
176+
wantUsedProxy: true,
177+
wantError: false,
178+
},
179+
{
180+
name: "gogit_HTTPS_PROXY",
181+
gitImpl: gogit.Implementation,
182+
url: "https://github.com/git-fixtures/basic",
183+
branch: "master",
184+
setupGitProxy: func(g *WithT, proxy *goproxy.ProxyHttpServer, proxyGotRequest *bool) (*git.AuthOptions, cleanupFunc) {
185+
var proxyHandler goproxy.FuncHttpsHandler = func(host string, ctx *goproxy.ProxyCtx) (*goproxy.ConnectAction, string) {
186+
// We don't check for user agent as this handler is only going to process CONNECT requests, and because Go's net/http
187+
// is the one making such a request on behalf of go-git, adding a check for the go net/http user agent (Go-http-client)
188+
// would only allow false positives from any request originating from Go's net/http.
189+
if strings.Contains(host, "github.com") {
190+
*proxyGotRequest = true
191+
return goproxy.OkConnect, host
192+
}
193+
// Reject if it isnt our request.
194+
return goproxy.RejectConnect, host
195+
}
196+
proxy.OnRequest().HandleConnect(proxyHandler)
197+
198+
// go-git does not allow to use an HTTPS proxy and a custom root CA at the same time.
199+
// See https://github.com/fluxcd/source-controller/pull/524#issuecomment-1006673163.
200+
return nil, func() {}
201+
},
202+
shortTimeout: false,
203+
wantUsedProxy: true,
204+
wantError: false,
205+
},
206+
{
207+
name: "gogit_NO_PROXY",
208+
gitImpl: gogit.Implementation,
209+
url: "https://192.0.2.1/bar/test-reponame",
210+
branch: "main",
211+
setupGitProxy: func(g *WithT, proxy *goproxy.ProxyHttpServer, proxyGotRequest *bool) (*git.AuthOptions, cleanupFunc) {
212+
var proxyHandler goproxy.FuncHttpsHandler = func(host string, ctx *goproxy.ProxyCtx) (*goproxy.ConnectAction, string) {
213+
// We shouldn't hit the proxy so we just want to check for any interaction, then reject.
214+
*proxyGotRequest = true
215+
return goproxy.RejectConnect, host
216+
}
217+
proxy.OnRequest().HandleConnect(proxyHandler)
218+
219+
return nil, func() {}
220+
},
221+
shortTimeout: true,
222+
wantUsedProxy: false,
223+
wantError: true,
224+
},
225+
// TODO: Add a NO_PROXY test for libgit2 once the version of libgit2 used by the source controller is updated to a version that includes
226+
// the NO_PROXY functionality
227+
// This PR introduces the functionality in libgit2: https://github.com/libgit2/libgit2/pull/6026
228+
}
229+
230+
for _, tt := range cases {
231+
t.Run(tt.name, func(t *testing.T) {
232+
g := NewWithT(t)
233+
234+
// Run a proxy server.
235+
proxy := goproxy.NewProxyHttpServer()
236+
proxy.Verbose = true
237+
238+
proxyGotRequest := false
239+
authOpts, cleanup := tt.setupGitProxy(g, proxy, &proxyGotRequest)
240+
defer cleanup()
241+
242+
proxyServer := http.Server{
243+
Addr: proxyAddr,
244+
Handler: proxy,
245+
}
246+
l, err := net.Listen("tcp", proxyServer.Addr)
247+
g.Expect(err).ToNot(HaveOccurred())
248+
go proxyServer.Serve(l)
249+
defer proxyServer.Close()
250+
251+
// Set the proxy env vars for both HTTP and HTTPS because go-git caches them.
252+
os.Setenv("HTTPS_PROXY", fmt.Sprintf("http://%s", proxyAddr))
253+
defer os.Unsetenv("HTTPS_PROXY")
254+
255+
os.Setenv("HTTP_PROXY", fmt.Sprintf("http://%s", proxyAddr))
256+
defer os.Unsetenv("HTTP_PROXY")
257+
258+
os.Setenv("NO_PROXY", "*.0.2.1")
259+
defer os.Unsetenv("NO_PROXY")
260+
261+
// Checkout the repo.
262+
checkoutStrategy, err := strategy.CheckoutStrategyForImplementation(context.TODO(), tt.gitImpl, git.CheckoutOptions{
263+
Branch: tt.branch,
264+
})
265+
g.Expect(err).ToNot(HaveOccurred())
266+
267+
tmpDir, err := os.MkdirTemp("", "test-checkout")
268+
g.Expect(err).ToNot(HaveOccurred())
269+
defer os.RemoveAll(tmpDir)
270+
271+
// for the NO_PROXY test we dont want to wait the 30s for it to timeout/fail, so shorten the timeout
272+
checkoutCtx := context.TODO()
273+
if tt.shortTimeout {
274+
var cancel context.CancelFunc
275+
checkoutCtx, cancel = context.WithTimeout(context.TODO(), 1*time.Second)
276+
defer cancel()
277+
}
278+
279+
_, err = checkoutStrategy.Checkout(checkoutCtx, tmpDir, tt.url, authOpts)
280+
if tt.wantError {
281+
g.Expect(err).To(HaveOccurred())
282+
} else {
283+
g.Expect(err).ToNot(HaveOccurred())
284+
}
285+
286+
g.Expect(proxyGotRequest).To(Equal(tt.wantUsedProxy))
287+
288+
})
289+
}
290+
}

0 commit comments

Comments
 (0)