Debian Codegraph @

csp.go

raw symbols SCIP
1 package secure
2
3 import (
4 "context"
5 "crypto/rand"
6 "encoding/base64"
7 "io"
8 "net/http"
9 )
10
11 type key int
12
13 const cspNonceKey key = iota
14
15 // CSPNonce returns the nonce value associated with the present request. If no nonce has been generated it returns an empty string.
16 func CSPNonce(c context.Context) string {
17 if val, ok := c.Value(cspNonceKey).(string); ok {
18 return val
19 }
20
21 return ""
22 }
23
24 // WithCSPNonce returns a context derived from ctx containing the given nonce as a value.
25 //
26 // This is intended for testing or more advanced use-cases;
27 // For ordinary HTTP handlers, clients can rely on this package's middleware to populate the CSP nonce in the context.
28 func WithCSPNonce(ctx context.Context, nonce string) context.Context {
29 return context.WithValue(ctx, cspNonceKey, nonce)
30 }
31
32 func withCSPNonce(r *http.Request, nonce string) *http.Request {
33 return r.WithContext(WithCSPNonce(r.Context(), nonce))
34 }
35
36 func cspRandNonce() string {
37 var buf [cspNonceSize]byte
38 _, err := io.ReadFull(rand.Reader, buf[:])
39 if err != nil {
40 panic("CSP Nonce rand.Reader failed" + err.Error())
41 }
42
43 return base64.RawStdEncoding.EncodeToString(buf[:])
44 }