forked from imroc/req
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdigest.go
More file actions
225 lines (206 loc) · 5.24 KB
/
digest.go
File metadata and controls
225 lines (206 loc) · 5.24 KB
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
package req
import (
"bytes"
"io"
"net/http"
"sync"
"github.com/icholy/digest"
"github.com/imroc/req/v3/internal/header"
)
// cchal is a cached challenge and the number of times it's been used.
type cchal struct {
c *digest.Challenge
n int
}
type digestAuth struct {
Username string
Password string
HttpClient *http.Client
cache map[string]*cchal
cacheMu sync.Mutex
}
func (da *digestAuth) digest(req *http.Request, chal *digest.Challenge, count int) (*digest.Credentials, error) {
opt := digest.Options{
Method: req.Method,
URI: req.URL.RequestURI(),
GetBody: req.GetBody,
Count: count,
Username: da.Username,
Password: da.Password,
}
return digest.Digest(chal, opt)
}
// challenge returns a cached challenge and count for the provided request
func (da *digestAuth) challenge(req *http.Request) (*digest.Challenge, int, bool) {
da.cacheMu.Lock()
defer da.cacheMu.Unlock()
host := req.URL.Hostname()
cc, ok := da.cache[host]
if !ok {
return nil, 0, false
}
cc.n++
return cc.c, cc.n, true
}
// prepare attempts to find a cached challenge that matches the
// requested domain, and use it to set the Authorization header
func (da *digestAuth) prepare(req *http.Request) error {
// add cookies
if da.HttpClient.Jar != nil {
for _, cookie := range da.HttpClient.Jar.Cookies(req.URL) {
req.AddCookie(cookie)
}
}
// add auth
chal, count, ok := da.challenge(req)
if !ok {
return nil
}
cred, err := da.digest(req, chal, count)
if err != nil {
return err
}
if cred != nil {
req.Header.Set("Authorization", cred.String())
}
return nil
}
func (da *digestAuth) HttpRoundTripWrapperFunc(rt http.RoundTripper) HttpRoundTripFunc {
return func(req *http.Request) (resp *http.Response, err error) {
clone, err := cloner(req)
if err != nil {
return nil, err
}
// make a copy of the request
first, err := clone()
if err != nil {
return nil, err
}
// prepare the first request using a cached challenge
if err := da.prepare(first); err != nil {
return nil, err
}
// the first request will either succeed or return a 401
res, err := rt.RoundTrip(first)
if err != nil || res.StatusCode != http.StatusUnauthorized {
return res, err
}
// drain and close the first message body
_, _ = io.Copy(io.Discard, res.Body)
_ = res.Body.Close()
// find and cache the challenge
host := req.URL.Hostname()
chal, err := digest.FindChallenge(res.Header)
if err != nil {
// existing cached challenge didn't work, so remove it
da.cacheMu.Lock()
delete(da.cache, host)
da.cacheMu.Unlock()
if err == digest.ErrNoChallenge {
return res, nil
}
return nil, err
} else {
// found new challenge, so cache it
da.cacheMu.Lock()
da.cache[host] = &cchal{c: chal}
da.cacheMu.Unlock()
}
// make a second copy of the request
second, err := clone()
if err != nil {
return nil, err
}
// prepare the second request based on the new challenge
if err := da.prepare(second); err != nil {
return nil, err
}
return rt.RoundTrip(second)
}
}
// create response middleware for http digest authentication.
func handleDigestAuthFunc(username, password string) ResponseMiddleware {
return func(client *Client, resp *Response) error {
if resp.Err != nil || resp.StatusCode != http.StatusUnauthorized {
return nil
}
auth, err := createDigestAuth(resp.Request.RawRequest, resp.Response, username, password)
if err != nil {
return err
}
r := resp.Request
req := *r.RawRequest
if req.Body != nil {
err = parseRequestBody(client, r) // re-setup body
if err != nil {
return err
}
if r.GetBody != nil {
body, err := r.GetBody()
if err != nil {
return err
}
req.Body = body
req.GetBody = r.GetBody
}
}
if req.Header == nil {
req.Header = make(http.Header)
}
req.Header.Set(header.Authorization, auth)
resp.Response, err = client.httpClient.Do(&req)
return err
}
}
func createDigestAuth(req *http.Request, resp *http.Response, username, password string) (auth string, err error) {
chal, err := digest.FindChallenge(resp.Header)
if err != nil {
return "", err
}
cred, err := digest.Digest(chal, digest.Options{
Username: username,
Password: password,
Method: req.Method,
URI: req.URL.RequestURI(),
GetBody: req.GetBody,
Count: 1,
})
if err != nil {
return "", err
}
return cred.String(), nil
}
// cloner returns a function which makes clones of the provided request
func cloner(req *http.Request) (func() (*http.Request, error), error) {
getbody := req.GetBody
// if there's no GetBody function set we have to copy the body
// into memory to use for future clones
if getbody == nil {
if req.Body == nil || req.Body == http.NoBody {
getbody = func() (io.ReadCloser, error) {
return http.NoBody, nil
}
} else {
body, err := io.ReadAll(req.Body)
if err != nil {
return nil, err
}
if err := req.Body.Close(); err != nil {
return nil, err
}
getbody = func() (io.ReadCloser, error) {
return io.NopCloser(bytes.NewReader(body)), nil
}
}
}
return func() (*http.Request, error) {
clone := req.Clone(req.Context())
body, err := getbody()
if err != nil {
return nil, err
}
clone.Body = body
clone.GetBody = getbody
return clone, nil
}, nil
}