github.com/google/go-safeweb@v0.0.0-20231219055052-64d8cfc90fbb/tests/integration/xsrf/xsrf_test.go (about) 1 // Copyright 2020 Google LLC 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 // https://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_test 16 17 import ( 18 "net/http/httptest" 19 "strings" 20 "testing" 21 22 "github.com/google/go-safeweb/safehttp" 23 "github.com/google/go-safeweb/safehttp/plugins/xsrf/xsrfhtml" 24 "github.com/google/safehtml/template" 25 ) 26 27 func TestServeMuxInstallXSRF(t *testing.T) { 28 mb := safehttp.NewServeMuxConfig(nil) 29 it := xsrfhtml.Interceptor{SecretAppKey: "testSecretAppKey"} 30 mb.Intercept(&it) 31 mux := mb.Mux() 32 33 handler := safehttp.HandlerFunc(func(w safehttp.ResponseWriter, r *safehttp.IncomingRequest) safehttp.Result { 34 fns := map[string]interface{}{ 35 "XSRFToken": func() string { return "WrongToken" }, 36 } 37 t := template.Must(template.New("name").Funcs(fns).Parse(`<form><input type="hidden" name="token" value="{{XSRFToken}}">{{.}}</form>`)) 38 39 return safehttp.ExecuteTemplateWithFuncs(w, t, "Content", fns) 40 }) 41 mux.Handle("/bar", safehttp.MethodGet, handler) 42 43 rr := httptest.NewRecorder() 44 45 req := httptest.NewRequest(safehttp.MethodGet, "https://foo.com/bar", nil) 46 47 mux.ServeHTTP(rr, req) 48 49 if got, want := rr.Code, safehttp.StatusOK; got != int(want) { 50 t.Errorf("rr.Code got: %v want: %v", got, int(want)) 51 } 52 53 if gotBody := rr.Body.String(); strings.Contains(gotBody, "WrongToken") { 54 t.Errorf("response body: got %q, injection failed", gotBody) 55 } 56 57 }