Debian Codegraph @

plumbing/transport/http/internal/test/test_utils.go

raw
1 package test
2
3 import (
4 "encoding/base64"
5 "strings"
6 "sync/atomic"
7
8 "github.com/elazarl/goproxy"
9 )
10
11 func SetupHTTPSProxy(proxy *goproxy.ProxyHttpServer, proxiedRequests *int32) {
12 var proxyHandler goproxy.FuncHttpsHandler = func(host string, ctx *goproxy.ProxyCtx) (*goproxy.ConnectAction, string) {
13 if strings.Contains(host, "github.com") {
14 user, pass, _ := ParseBasicAuth(ctx.Req.Header.Get("Proxy-Authorization"))
15 if user != "user" || pass != "pass" {
16 return goproxy.RejectConnect, host
17 }
18 atomic.AddInt32(proxiedRequests, 1)
19 return goproxy.OkConnect, host
20 }
21 // Reject if it isn't our request.
22 return goproxy.RejectConnect, host
23 }
24 proxy.OnRequest().HandleConnect(proxyHandler)
25 }
26
27 // adapted from https://github.com/golang/go/blob/2ef70d9d0f98832c8103a7968b195e560a8bb262/src/net/http/request.go#L959
28 func ParseBasicAuth(auth string) (username, password string, ok bool) {
29 const prefix = "Basic "
30 if len(auth) < len(prefix) || !strings.EqualFold(auth[:len(prefix)], prefix) {
31 return "", "", false
32 }
33 c, err := base64.StdEncoding.DecodeString(auth[len(prefix):])
34 if err != nil {
35 return "", "", false
36 }
37 cs := string(c)
38 username, password, ok = strings.Cut(cs, ":")
39 if !ok {
40 return "", "", false
41 }
42 return username, password, true
43 }