github.com/google/go-safeweb@v0.0.0-20231219055052-64d8cfc90fbb/safehttp/plugins/csp/trustedtypes.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 csp 16 17 import ( 18 "strings" 19 20 "github.com/google/go-safeweb/safehttp" 21 "github.com/google/go-safeweb/safehttp/plugins/csp/internalunsafecsp" 22 ) 23 24 // TrustedTypesPolicy policy can be used to create a new CSP which makes 25 // dangerous web API functions secure by default. 26 // 27 // See https://web.dev/trusted-types for more info. 28 type TrustedTypesPolicy struct { 29 // ReportURI controls the report-uri directive. If ReportUri is empty, no report-uri 30 // directive will be set. 31 ReportURI string 32 } 33 34 // Serialize serializes this policy for use in a Content-Security-Policy header 35 // or in a Content-Security-Policy-Report-Only header. A nonce will be provided 36 // to Serialize which can be used in 'nonce-{random-nonce}' values in directives. 37 func (t TrustedTypesPolicy) Serialize(nonce string, _ safehttp.InterceptorConfig) string { 38 var b strings.Builder 39 b.WriteString("require-trusted-types-for 'script'") 40 41 if t.ReportURI != "" { 42 b.WriteString("; report-uri ") 43 b.WriteString(t.ReportURI) 44 } 45 46 return b.String() 47 } 48 49 // Match matches strict policies overrides. 50 func (TrustedTypesPolicy) Match(cfg safehttp.InterceptorConfig) bool { 51 _, ok := cfg.(internalunsafecsp.DisableTrustedTypes) 52 return ok 53 } 54 55 // Overridden checks the override level. 56 func (TrustedTypesPolicy) Overridden(cfg safehttp.InterceptorConfig) (disabled, reportOnly bool) { 57 disable := cfg.(internalunsafecsp.DisableTrustedTypes) 58 return disable.SkipReports, true 59 }