github.com/google/go-safeweb@v0.0.0-20231219055052-64d8cfc90fbb/safehttp/plugins/framing/framing.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 framing provides utilities to install a comprehensive framing protection.
    16  package framing
    17  
    18  import (
    19  	"github.com/google/go-safeweb/safehttp"
    20  	"github.com/google/go-safeweb/safehttp/plugins/csp"
    21  
    22  	"github.com/google/go-safeweb/safehttp/plugins/fetchmetadata"
    23  	"github.com/google/go-safeweb/safehttp/plugins/framing/internalunsafeframing"
    24  )
    25  
    26  // Interceptors returns all interceptors needed for a comprehensive framing protection.
    27  func Interceptors(reportURI string) []safehttp.Interceptor {
    28  	return []safehttp.Interceptor{
    29  		fetchmetadata.FramingIsolationPolicy(),
    30  		csp.Interceptor{Policy: csp.FramingPolicy{ReportURI: reportURI}},
    31  		xfoInterceptor{},
    32  	}
    33  }
    34  
    35  type xfoInterceptor struct{}
    36  
    37  func (xfoInterceptor) Before(w safehttp.ResponseWriter, r *safehttp.IncomingRequest, cfg safehttp.InterceptorConfig) safehttp.Result {
    38  	xfo := w.Header().Claim("X-Frame-Options")
    39  	switch cfg.(type) {
    40  	case internalunsafeframing.Disable, internalunsafeframing.AllowList:
    41  		// X-Frame-Options doesn't support allowlists.
    42  		// We rely on CSP to do the restriction on this value.
    43  		xfo([]string{"ALLOWALL"})
    44  	default:
    45  		xfo([]string{"SAMEORIGIN"})
    46  	}
    47  	return safehttp.NotWritten()
    48  }
    49  
    50  func (xfoInterceptor) Commit(w safehttp.ResponseHeadersWriter, r *safehttp.IncomingRequest, resp safehttp.Response, cfg safehttp.InterceptorConfig) {
    51  }
    52  
    53  func (xfoInterceptor) Match(cfg safehttp.InterceptorConfig) bool {
    54  	switch cfg.(type) {
    55  	case internalunsafeframing.Disable, internalunsafeframing.AllowList:
    56  		return true
    57  	}
    58  	return false
    59  }