go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/server/auth/xsrf/xsrf_test.go (about) 1 // Copyright 2015 The LUCI Authors. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package xsrf 16 17 import ( 18 "context" 19 "html/template" 20 "net/http" 21 "net/http/httptest" 22 "net/url" 23 "strings" 24 "testing" 25 "time" 26 27 "go.chromium.org/luci/common/clock/testclock" 28 29 "go.chromium.org/luci/server/router" 30 "go.chromium.org/luci/server/secrets" 31 "go.chromium.org/luci/server/secrets/testsecrets" 32 33 . "github.com/smartystreets/goconvey/convey" 34 ) 35 36 func TestXsrf(t *testing.T) { 37 Convey("Token + Check", t, func() { 38 c := makeContext() 39 tok, err := Token(c) 40 So(err, ShouldBeNil) 41 So(Check(c, tok), ShouldBeNil) 42 So(Check(c, tok+"abc"), ShouldNotBeNil) 43 }) 44 45 Convey("TokenField works", t, func() { 46 c := makeContext() 47 So(TokenField(c), ShouldResemble, 48 template.HTML("<input type=\"hidden\" name=\"xsrf_token\" "+ 49 "value=\"AXsiX2kiOiIxNDQyMjcwNTIwMDAwIn1ceiDv1yfNK9OHcdb209l3fM4p_gn-Uaembaa8gr3WXg\">")) 50 }) 51 52 Convey("Middleware works", t, func() { 53 c := makeContext() 54 tok, _ := Token(c) 55 56 h := func(c *router.Context) { 57 c.Writer.Write([]byte("hi")) 58 } 59 mc := router.NewMiddlewareChain(WithTokenCheck) 60 61 // Has token -> works. 62 rec := httptest.NewRecorder() 63 req := makeRequest(c, tok) 64 router.RunMiddleware(&router.Context{ 65 Writer: rec, 66 Request: req, 67 }, mc, h) 68 So(rec.Code, ShouldEqual, 200) 69 70 // No token. 71 rec = httptest.NewRecorder() 72 req = makeRequest(c, "") 73 router.RunMiddleware(&router.Context{ 74 Writer: rec, 75 Request: req, 76 }, mc, h) 77 So(rec.Code, ShouldEqual, 403) 78 79 // Bad token. 80 rec = httptest.NewRecorder() 81 req = makeRequest(c, "blah") 82 router.RunMiddleware(&router.Context{ 83 Writer: rec, 84 Request: req, 85 }, mc, h) 86 So(rec.Code, ShouldEqual, 403) 87 }) 88 } 89 90 func makeContext() context.Context { 91 c := secrets.Use(context.Background(), &testsecrets.Store{}) 92 c, _ = testclock.UseTime(c, time.Unix(1442270520, 0)) 93 return c 94 } 95 96 func makeRequest(ctx context.Context, tok string) *http.Request { 97 body := url.Values{} 98 if tok != "" { 99 body.Add("xsrf_token", tok) 100 } 101 req, _ := http.NewRequestWithContext(ctx, "POST", "https://example.com", strings.NewReader(body.Encode())) 102 req.Header.Add("Content-Type", "application/x-www-form-urlencoded") 103 return req 104 }