github.com/google/go-safeweb@v0.0.0-20231219055052-64d8cfc90fbb/examples/echo/security/web/web_test.go (about) 1 // Copyright 2022 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 web 16 17 import ( 18 "fmt" 19 "net/http/httptest" 20 "testing" 21 22 "github.com/google/go-safeweb/safehttp" 23 "github.com/google/safehtml" 24 ) 25 26 func TestNewMuxConfig(t *testing.T) { 27 tests := []struct { 28 name string 29 config *safehttp.ServeMuxConfig 30 addr string 31 hasHSTS bool 32 }{ 33 { 34 name: "development mux config", 35 config: NewMuxConfigDev(8080), 36 addr: "https://localhost:8080", 37 hasHSTS: false, 38 }, 39 { 40 name: "production mux config", 41 config: NewMuxConfig("localhost:8080"), 42 addr: "https://localhost:8080", 43 hasHSTS: true, 44 }, 45 } 46 47 for _, tt := range tests { 48 t.Run(tt.name, func(t *testing.T) { 49 mux := tt.config.Mux() 50 h := safehttp.HandlerFunc(func(w safehttp.ResponseWriter, r *safehttp.IncomingRequest) safehttp.Result { 51 return w.Write(safehtml.HTMLEscaped("<h1>Hello World!</h1>")) 52 }) 53 mux.Handle("/spaghetti", safehttp.MethodGet, h) 54 55 req := httptest.NewRequest(safehttp.MethodGet, fmt.Sprintf("%s/spaghetti", tt.addr), nil) 56 rw := httptest.NewRecorder() 57 mux.ServeHTTP(rw, req) 58 59 hasHSTSHeader := rw.Header().Get("Strict-Transport-Security") != "" 60 if tt.hasHSTS && !hasHSTSHeader { 61 t.Errorf("expected \"Strict-Transport-Security\" header since HTST is enabled") 62 } 63 if !tt.hasHSTS && hasHSTSHeader { 64 t.Errorf("unexpected \"Strict-Transport-Security\" header since HTST is disabled") 65 } 66 }) 67 } 68 }