github.com/google/go-safeweb@v0.0.0-20231219055052-64d8cfc90fbb/safehttp/plugins/fetchmetadata/fetchmetadata_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 fetchmetadata_test
    16  
    17  import (
    18  	"net/http"
    19  	"testing"
    20  
    21  	"github.com/google/go-cmp/cmp"
    22  	"github.com/google/go-safeweb/safehttp/plugins/fetchmetadata"
    23  
    24  	"github.com/google/go-safeweb/safehttp"
    25  	"github.com/google/go-safeweb/safehttp/safehttptest"
    26  )
    27  
    28  type testHeaders struct {
    29  	name, method, site, mode, dest string
    30  }
    31  
    32  func TestReportOnly(t *testing.T) {
    33  	type reportTests struct {
    34  		name, site, mode, dest, block string
    35  	}
    36  	var tests []reportTests
    37  	for _, t := range allowedFIPHeaders {
    38  		tests = append(tests, reportTests{
    39  			name:  t.name,
    40  			site:  t.site,
    41  			mode:  t.mode,
    42  			dest:  t.dest,
    43  			block: "false",
    44  		})
    45  	}
    46  	for _, t := range disallowedFIPHeaders {
    47  		tests = append(tests, reportTests{
    48  			name:  t.name,
    49  			site:  t.site,
    50  			mode:  t.mode,
    51  			dest:  t.dest,
    52  			block: "true",
    53  		})
    54  	}
    55  	for _, test := range tests {
    56  		t.Run(test.name, func(t *testing.T) {
    57  			req := safehttptest.NewRequest("GET", "https://spaghetti.com/carbonara", nil)
    58  			req.Header.Add("Sec-Fetch-Site", test.site)
    59  			req.Header.Add("Sec-Fetch-Mode", test.mode)
    60  			req.Header.Add("Sec-Fetch-Dest", test.dest)
    61  			fakeRW, rr := safehttptest.NewFakeResponseWriter()
    62  
    63  			p := fetchmetadata.FramingIsolationPolicy()
    64  			p.ReportOnly = true
    65  			p.Before(fakeRW, req, nil)
    66  
    67  			if want, got := safehttp.StatusOK, safehttp.StatusCode(rr.Code); want != got {
    68  				t.Errorf("rr.Code got: %v want: %v", got, want)
    69  			}
    70  			if diff := cmp.Diff(http.Header{}, rr.Header()); diff != "" {
    71  				t.Errorf("rr.Header() mismatch (-want +got):\n%s", diff)
    72  			}
    73  			if want, got := "", rr.Body.String(); got != want {
    74  				t.Errorf("rr.Body.String() got: %q want: %q", got, want)
    75  			}
    76  		})
    77  	}
    78  }