github.com/google/go-safeweb@v0.0.0-20231219055052-64d8cfc90fbb/examples/trustedtypes/server.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  // Implements a simple server presenting DOM XSS protection with Trusted Types.
    16  //
    17  // Endpoints:
    18  //   - /safe#<script>alert(1)</script>
    19  //   - /unsafe#<script>alert(1)</script>
    20  package main
    21  
    22  import (
    23  	"log"
    24  	"net"
    25  	"net/http"
    26  
    27  	"github.com/google/safehtml/template"
    28  
    29  	"github.com/google/go-safeweb/safehttp"
    30  	"github.com/google/go-safeweb/safehttp/plugins/csp"
    31  	"github.com/google/go-safeweb/safehttp/plugins/htmlinject"
    32  )
    33  
    34  func main() {
    35  	mb, addr := newServeMuxConfig()
    36  	mux := mb.Mux()
    37  
    38  	safeTmpl, _ := loadTemplate("safe.html")
    39  	mux.Handle("/safe", safehttp.MethodGet, safehttp.HandlerFunc(handleTemplate(safeTmpl)))
    40  
    41  	unsafeTmpl, _ := loadTemplate("unsafe.html")
    42  	mux.Handle("/unsafe", safehttp.MethodGet, safehttp.HandlerFunc(handleTemplate(unsafeTmpl)))
    43  
    44  	log.Printf("Visit http://%s\n", addr)
    45  	log.Printf("Listening on %s...\n", addr)
    46  	log.Fatal(http.ListenAndServe(addr, mux))
    47  }
    48  
    49  func newServeMuxConfig() (*safehttp.ServeMuxConfig, string) {
    50  	host := "localhost"
    51  	port := "8080"
    52  	addr := net.JoinHostPort(host, port)
    53  	mc := safehttp.NewServeMuxConfig(nil)
    54  	for _, i := range csp.Default("") {
    55  		mc.Intercept(i)
    56  	}
    57  	return mc, addr
    58  }
    59  
    60  func loadTemplate(src string) (*template.Template, error) {
    61  	tmplSrc, err := template.TrustedSourceFromConstantDir("", template.TrustedSource{}, src)
    62  	if err != nil {
    63  		return nil, err
    64  	}
    65  
    66  	tmpl := template.Must(htmlinject.LoadFiles(nil, htmlinject.LoadConfig{}, tmplSrc))
    67  	return tmpl, nil
    68  }
    69  
    70  func handleTemplate(tmpl safehttp.Template) func(w safehttp.ResponseWriter, req *safehttp.IncomingRequest) safehttp.Result {
    71  	return func(w safehttp.ResponseWriter, req *safehttp.IncomingRequest) safehttp.Result {
    72  		return safehttp.ExecuteTemplate(w, tmpl, nil)
    73  	}
    74  }