| 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 |
|
| 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 |
|
| 25 |
|
| 26 |
|
| 27 |
|
| 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 |
} |