github.com/google/go-safeweb@v0.0.0-20231219055052-64d8cfc90fbb/safehttp/plugins/staticheaders/staticheaders.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 staticheaders provides a safehttp.Interceptor which sets security
    16  // sensitive headers on every response.
    17  //
    18  // X-Content-Type-Options: nosniff - tells browsers to not to sniff the
    19  // Content-Type of responses (https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Content-Type-Options).
    20  //
    21  // X-XSS-Protection: 0 - tells the browser to disable any built in XSS filters.
    22  // These built in XSS filters are unnecessary when other, stronger, protections
    23  // are available and can introduce cross-site leaks vulnerabilities
    24  // (https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-XSS-Protection).
    25  //
    26  // # Usage
    27  //
    28  // Install an instance of Interceptor using safehttp.ServerMux.Install.
    29  package staticheaders
    30  
    31  import (
    32  	"github.com/google/go-safeweb/safehttp"
    33  )
    34  
    35  // Interceptor claims and sets static headers on responses.
    36  // The zero value is valid and ready to use.
    37  type Interceptor struct{}
    38  
    39  var _ safehttp.Interceptor = Interceptor{}
    40  
    41  // Before claims and sets the following headers:
    42  //   - X-Content-Type-Options: nosniff
    43  //   - X-XSS-Protection: 0
    44  func (Interceptor) Before(w safehttp.ResponseWriter, r *safehttp.IncomingRequest, _ safehttp.InterceptorConfig) safehttp.Result {
    45  	h := w.Header()
    46  	setXCTO := h.Claim("X-Content-Type-Options")
    47  	setXXP := h.Claim("X-XSS-Protection")
    48  
    49  	setXCTO([]string{"nosniff"})
    50  	setXXP([]string{"0"})
    51  	return safehttp.NotWritten()
    52  }
    53  
    54  // Commit is a no-op, required to satisfy the safehttp.Interceptor interface.
    55  func (Interceptor) Commit(w safehttp.ResponseHeadersWriter, r *safehttp.IncomingRequest, resp safehttp.Response, _ safehttp.InterceptorConfig) {
    56  }
    57  
    58  // Match returns false since there are no supported configurations.
    59  func (Interceptor) Match(safehttp.InterceptorConfig) bool {
    60  	return false
    61  }