-
Notifications
You must be signed in to change notification settings - Fork 18
/
api.go
82 lines (68 loc) · 2.13 KB
/
api.go
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
// Copyright 2023 Princess B33f Heavy Industries / Dave Shanley
// SPDX-License-Identifier: MIT
package daemon
import (
"crypto/tls"
"github.com/pb33f/wiretap/config"
"github.com/pterm/pterm"
"net/http"
"net/url"
"github.com/pb33f/wiretap/shared"
)
type wiretapTransport struct {
capturedCookieHeaders []string
originalTransport http.RoundTripper
}
func newWiretapTransport() *wiretapTransport {
// Disable ssl cert checks
http.DefaultTransport.(*http.Transport).TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
return &wiretapTransport{
originalTransport: http.DefaultTransport,
}
}
func (c *wiretapTransport) RoundTrip(r *http.Request) (*http.Response, error) {
resp, err := c.originalTransport.RoundTrip(r)
if resp != nil {
cookie := resp.Header.Get("Set-Cookie")
if cookie != "" {
c.capturedCookieHeaders = append(c.capturedCookieHeaders, cookie)
}
}
return resp, err
}
func (ws *WiretapService) callAPI(req *http.Request) (*http.Response, error) {
tr := newWiretapTransport()
client := &http.Client{Transport: tr}
configStore, _ := ws.controlsStore.Get(shared.ConfigKey)
// create a new request from the original request, but replace the path
wiretapConfig := configStore.(*shared.WiretapConfiguration)
// lookup path and determine if we need to redirect it.
replaced := config.RewritePath(req.URL.Path, wiretapConfig)
if replaced != "" {
newUrl, _ := url.Parse(replaced)
if req.URL.RawQuery != "" {
newUrl.RawQuery = req.URL.RawQuery
}
pterm.Info.Printf("[wiretap] Re-writing path '%s' to '%s'\n", req.URL.String(), newUrl.String())
req.URL = newUrl
}
// re-write referer
if req.Header.Get("Referer") != "" {
// retain original referer for logging
req.Header.Set("X-Original-Referer", req.Header.Get("Referer"))
req.Header.Set("Referer", reconstructURL(req,
wiretapConfig.RedirectProtocol,
wiretapConfig.RedirectHost,
wiretapConfig.RedirectPort))
}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
if len(tr.capturedCookieHeaders) > 0 {
if resp.Header.Get("Set-Cookie") == "" {
resp.Header.Set("Set-Cookie", tr.capturedCookieHeaders[0])
}
}
return resp, nil
}