Debian Codegraph @

spnego/http_test.go

raw
1 package spnego
2
3 import (
4 "bytes"
5 "crypto/rand"
6 "encoding/hex"
7 "fmt"
8 "io"
9 "io/ioutil"
10 "log"
11 "mime/multipart"
12 "net/http"
13 "net/http/httptest"
14 "os"
15 "sync"
16 "testing"
17
18 "github.com/stretchr/testify/assert"
19 "gopkg.in/jcmturner/goidentity.v3"
20 "gopkg.in/jcmturner/gokrb5.v7/client"
21 "gopkg.in/jcmturner/gokrb5.v7/config"
22 "gopkg.in/jcmturner/gokrb5.v7/keytab"
23 "gopkg.in/jcmturner/gokrb5.v7/service"
24 "gopkg.in/jcmturner/gokrb5.v7/test"
25 "gopkg.in/jcmturner/gokrb5.v7/test/testdata"
26 )
27
28 func TestClient_SetSPNEGOHeader(t *testing.T) {
29 test.Integration(t)
30 b, _ := hex.DecodeString(testdata.TESTUSER1_KEYTAB)
31 kt := keytab.New()
32 kt.Unmarshal(b)
33 c, _ := config.NewConfigFromString(testdata.TEST_KRB5CONF)
34 addr := os.Getenv("TEST_KDC_ADDR")
35 if addr == "" {
36 addr = testdata.TEST_KDC_ADDR
37 }
38 c.Realms[0].KDC = []string{addr + ":" + testdata.TEST_KDC}
39 l := log.New(os.Stderr, "SPNEGO Client:", log.LstdFlags)
40 cl := client.NewClientWithKeytab("testuser1", "TEST.GOKRB5", kt, c, client.Logger(l))
41
42 err := cl.Login()
43 if err != nil {
44 t.Fatalf("error on AS_REQ: %v\n", err)
45 }
46 urls := []string{
47 "http://cname.test.gokrb5",
48 "http://host.test.gokrb5",
49 }
50 paths := []string{
51 "/modkerb/index.html",
52 //"/modgssapi/index.html",
53 }
54 for _, url := range urls {
55 for _, p := range paths {
56 r, _ := http.NewRequest("GET", url+p, nil)
57 httpResp, err := http.DefaultClient.Do(r)
58 if err != nil {
59 t.Fatalf("%s request error: %v", url+p, err)
60 }
61 assert.Equal(t, http.StatusUnauthorized, httpResp.StatusCode, "Status code in response to client with no SPNEGO not as expected")
62
63 err = SetSPNEGOHeader(cl, r, "")
64 if err != nil {
65 t.Fatalf("error setting client SPNEGO header: %v", err)
66 }
67
68 httpResp, err = http.DefaultClient.Do(r)
69 if err != nil {
70 t.Fatalf("%s request error: %v\n", url+p, err)
71 }
72 assert.Equal(t, http.StatusOK, httpResp.StatusCode, "Status code in response to client SPNEGO request not as expected")
73 }
74 }
75 }
76
77 func TestSPNEGOHTTPClient(t *testing.T) {
78 test.Integration(t)
79 b, _ := hex.DecodeString(testdata.TESTUSER1_KEYTAB)
80 kt := keytab.New()
81 kt.Unmarshal(b)
82 c, _ := config.NewConfigFromString(testdata.TEST_KRB5CONF)
83 addr := os.Getenv("TEST_KDC_ADDR")
84 if addr == "" {
85 addr = testdata.TEST_KDC_ADDR
86 }
87 c.Realms[0].KDC = []string{addr + ":" + testdata.TEST_KDC}
88 l := log.New(os.Stderr, "SPNEGO Client:", log.LstdFlags)
89 cl := client.NewClientWithKeytab("testuser1", "TEST.GOKRB5", kt, c, client.Logger(l))
90
91 err := cl.Login()
92 if err != nil {
93 t.Fatalf("error on AS_REQ: %v\n", err)
94 }
95 urls := []string{
96 "http://cname.test.gokrb5",
97 "http://host.test.gokrb5",
98 }
99 // This path issues a redirect which the http client will automatically follow.
100 // It should cause a replay issue if the negInit token is sent in the first instance.
101 paths := []string{
102 "/modgssapi", // This issues a redirect which the http client will automatically follow. Could cause a replay issue
103 "/redirect",
104 }
105 for _, url := range urls {
106 for _, p := range paths {
107 r, _ := http.NewRequest("GET", url+p, nil)
108 httpCl := http.DefaultClient
109 httpCl.CheckRedirect = func(req *http.Request, via []*http.Request) error {
110 t.Logf("http client redirect: %+v", *req)
111 return nil
112 }
113 spnegoCl := NewClient(cl, httpCl, "")
114 httpResp, err := spnegoCl.Do(r)
115 if err != nil {
116 t.Fatalf("%s request error: %v", url+p, err)
117 }
118 assert.Equal(t, http.StatusOK, httpResp.StatusCode, "Status code in response to client SPNEGO request not as expected")
119 }
120 }
121 }
122
123 func TestService_SPNEGOKRB_NoAuthHeader(t *testing.T) {
124 s := httpServer()
125 defer s.Close()
126 r, _ := http.NewRequest("GET", s.URL, nil)
127 httpResp, err := http.DefaultClient.Do(r)
128 if err != nil {
129 t.Fatalf("Request error: %v\n", err)
130 }
131 assert.Equal(t, http.StatusUnauthorized, httpResp.StatusCode, "Status code in response to client with no SPNEGO not as expected")
132 assert.Equal(t, "Negotiate", httpResp.Header.Get("WWW-Authenticate"), "Negotiation header not set by server.")
133 }
134
135 func TestService_SPNEGOKRB_ValidUser(t *testing.T) {
136 test.Integration(t)
137
138 s := httpServer()
139 defer s.Close()
140 r, _ := http.NewRequest("GET", s.URL, nil)
141
142 cl := getClient()
143 err := SetSPNEGOHeader(cl, r, "HTTP/host.test.gokrb5")
144 if err != nil {
145 t.Fatalf("error setting client's SPNEGO header: %v", err)
146 }
147
148 httpResp, err := http.DefaultClient.Do(r)
149 if err != nil {
150 t.Fatalf("Request error: %v\n", err)
151 }
152 assert.Equal(t, http.StatusOK, httpResp.StatusCode, "Status code in response to client SPNEGO request not as expected")
153 }
154
155 func TestService_SPNEGOKRB_Replay(t *testing.T) {
156 test.Integration(t)
157
158 s := httpServer()
159 defer s.Close()
160 r1, _ := http.NewRequest("GET", s.URL, nil)
161
162 cl := getClient()
163 err := SetSPNEGOHeader(cl, r1, "HTTP/host.test.gokrb5")
164 if err != nil {
165 t.Fatalf("error setting client's SPNEGO header: %v", err)
166 }
167
168 // First request with this ticket should be accepted
169 httpResp, err := http.DefaultClient.Do(r1)
170 if err != nil {
171 t.Fatalf("Request error: %v\n", err)
172 }
173 assert.Equal(t, http.StatusOK, httpResp.StatusCode, "Status code in response to client SPNEGO request not as expected")
174
175 // Use ticket again should be rejected
176 httpResp, err = http.DefaultClient.Do(r1)
177 if err != nil {
178 t.Fatalf("Request error: %v\n", err)
179 }
180 assert.Equal(t, http.StatusUnauthorized, httpResp.StatusCode, "Status code in response to client with no SPNEGO not as expected. Expected a replay to be detected.")
181
182 // Form a 2nd ticket
183 r2, _ := http.NewRequest("GET", s.URL, nil)
184
185 err = SetSPNEGOHeader(cl, r2, "HTTP/host.test.gokrb5")
186 if err != nil {
187 t.Fatalf("error setting client's SPNEGO header: %v", err)
188 }
189
190 // First use of 2nd ticket should be accepted
191 httpResp, err = http.DefaultClient.Do(r2)
192 if err != nil {
193 t.Fatalf("Request error: %v\n", err)
194 }
195 assert.Equal(t, http.StatusOK, httpResp.StatusCode, "Status code in response to client SPNEGO request not as expected")
196
197 // Using the 1st ticket again should still be rejected
198 httpResp, err = http.DefaultClient.Do(r1)
199 if err != nil {
200 t.Fatalf("Request error: %v\n", err)
201 }
202 assert.Equal(t, http.StatusUnauthorized, httpResp.StatusCode, "Status code in response to client with no SPNEGO not as expected. Expected a replay to be detected.")
203
204 // Using the 2nd again should be rejected as replay
205 httpResp, err = http.DefaultClient.Do(r2)
206 if err != nil {
207 t.Fatalf("Request error: %v\n", err)
208 }
209 assert.Equal(t, http.StatusUnauthorized, httpResp.StatusCode, "Status code in response to client with no SPNEGO not as expected. Expected a replay to be detected.")
210 }
211
212 func TestService_SPNEGOKRB_ReplayCache_Concurrency(t *testing.T) {
213 test.Integration(t)
214
215 s := httpServer()
216 defer s.Close()
217 r1, _ := http.NewRequest("GET", s.URL, nil)
218
219 cl := getClient()
220 err := SetSPNEGOHeader(cl, r1, "HTTP/host.test.gokrb5")
221 if err != nil {
222 t.Fatalf("error setting client's SPNEGO header: %v", err)
223 }
224
225 r2, _ := http.NewRequest("GET", s.URL, nil)
226
227 err = SetSPNEGOHeader(cl, r2, "HTTP/host.test.gokrb5")
228 if err != nil {
229 t.Fatalf("error setting client's SPNEGO header: %v", err)
230 }
231
232 // Concurrent 1st requests should be OK
233 var wg sync.WaitGroup
234 wg.Add(2)
235 go httpGet(r1, &wg)
236 go httpGet(r2, &wg)
237 wg.Wait()
238
239 // A number of concurrent requests with the same ticket should be rejected due to replay
240 var wg2 sync.WaitGroup
241 noReq := 10
242 wg2.Add(noReq * 2)
243 for i := 0; i < noReq; i++ {
244 go httpGet(r1, &wg2)
245 go httpGet(r2, &wg2)
246 }
247 wg2.Wait()
248 }
249
250 func TestService_SPNEGOKRB_Upload(t *testing.T) {
251 test.Integration(t)
252
253 s := httpServer()
254 defer s.Close()
255
256 bodyBuf := &bytes.Buffer{}
257 bodyWriter := multipart.NewWriter(bodyBuf)
258
259 fileWriter, err := bodyWriter.CreateFormFile("uploadfile", "testfile.bin")
260 if err != nil {
261 t.Fatalf("error writing to buffer: %v", err)
262 }
263
264 data := make([]byte, 10240)
265 rand.Read(data)
266 br := bytes.NewReader(data)
267 _, err = io.Copy(fileWriter, br)
268 if err != nil {
269 t.Fatalf("error copying bytes: %v", err)
270 }
271 bodyWriter.Close()
272
273 r, _ := http.NewRequest("POST", s.URL, bodyBuf)
274 r.Header.Set("Content-Type", bodyWriter.FormDataContentType())
275
276 cl := getClient()
277 spnegoCl := NewClient(cl, nil, "HTTP/host.test.gokrb5")
278 httpResp, err := spnegoCl.Do(r)
279 if err != nil {
280 t.Fatalf("Request error: %v\n", err)
281 }
282 if httpResp.StatusCode != http.StatusOK {
283 bodyBytes, _ := ioutil.ReadAll(httpResp.Body)
284 bodyString := string(bodyBytes)
285 httpResp.Body.Close()
286 t.Errorf("unexpected code from http server (%d): %s", httpResp.StatusCode, bodyString)
287 }
288 }
289
290 func httpGet(r *http.Request, wg *sync.WaitGroup) {
291 defer wg.Done()
292 http.DefaultClient.Do(r)
293 }
294
295 func httpServer() *httptest.Server {
296 l := log.New(os.Stderr, "GOKRB5 Service Tests: ", log.Ldate|log.Ltime|log.Lshortfile)
297 b, _ := hex.DecodeString(testdata.HTTP_KEYTAB)
298 kt := keytab.New()
299 kt.Unmarshal(b)
300 th := http.HandlerFunc(testAppHandler)
301 s := httptest.NewServer(SPNEGOKRB5Authenticate(th, kt, service.Logger(l)))
302 return s
303 }
304
305 func testAppHandler(w http.ResponseWriter, r *http.Request) {
306 if r.Method == http.MethodPost {
307 maxUploadSize := int64(11240)
308 if err := r.ParseMultipartForm(maxUploadSize); err != nil {
309 http.Error(w, fmt.Sprintf("cannot parse multipart form: %v", err), http.StatusBadRequest)
310 return
311 }
312 r.Body = http.MaxBytesReader(w, r.Body, maxUploadSize)
313 file, _, err := r.FormFile("uploadfile")
314 if err != nil {
315 http.Error(w, "INVALID_FILE", http.StatusBadRequest)
316 return
317 }
318 defer file.Close()
319
320 // write out to /dev/null
321 _, err = io.Copy(ioutil.Discard, file)
322 if err != nil {
323 http.Error(w, "WRITE_ERR", http.StatusInternalServerError)
324 return
325 }
326 }
327 w.WriteHeader(http.StatusOK)
328 ctx := r.Context()
329 fmt.Fprintf(w, "<html>\nTEST.GOKRB5 Handler\nAuthenticed user: %s\nUser's realm: %s\n</html>",
330 ctx.Value(CTXKeyCredentials).(goidentity.Identity).UserName(),
331 ctx.Value(CTXKeyCredentials).(goidentity.Identity).Domain())
332 return
333 }
334
335 func getClient() *client.Client {
336 b, _ := hex.DecodeString(testdata.TESTUSER1_KEYTAB)
337 kt := keytab.New()
338 kt.Unmarshal(b)
339 c, _ := config.NewConfigFromString(testdata.TEST_KRB5CONF)
340 c.LibDefaults.NoAddresses = true
341 addr := os.Getenv("TEST_KDC_ADDR")
342 if addr == "" {
343 addr = testdata.TEST_KDC_ADDR
344 }
345 c.Realms[0].KDC = []string{addr + ":" + testdata.TEST_KDC}
346 c.Realms[0].KPasswdServer = []string{addr + ":464"}
347 cl := client.NewClientWithKeytab("testuser1", "TEST.GOKRB5", kt, c)
348 return cl
349 }