Categorygithub.com/gmsec26/go-csp-engine
modulepackage
1.0.0
Repository: https://github.com/gmsec26/go-csp-engine.git
Documentation: pkg.go.dev

# README

go-csp-engine GoDoc Build Status

Content Security Policy engine for Go/Golang. Unit test your CSP rules!

This allows you to check HTML and CSS for preflight CSP violations.

Features:

  • Checks script, img, audio, video, track, iframe, object, embed, applet, style, base tags.
  • Checks link tags for stylesheet, prefetch, prerender, icon, and manifest types.
  • Checks unsafe inline style and script tags for nonce & hash.
  • Check stylesheet @import and @font-face external URLs.

Known limitations:

  • Doesn't fetch imported/referenced URLs to check for post flight violations. Thus, it doesn't check that the imported external resources have valid hashes.
  • Doesn't check stylesheet declarations that access resources like background-image.
  • Doesn't check any network requests made by javascript.

Example

package main

import (
	"net/url"
	"strings"
  "log"

	csp "github.com/d4l3k/go-csp-engine"
)

func main() {
  policy, err := csp.ParsePolicy("default-src: 'self'; script-src: 'nonce-foo'; img-src https://cdn")
  if err != nil {
    log.Fatal(err)
  }
  page, err := url.Parse('http://example.com/bar/')
  if err != nil {
    log.Fatal(err)
  }
  valid, reports, err := csp.ValidatePage(policy, *page, strings.NewReader(`
    <link rel="stylesheet" href="./foo.css">
    <script nonce="foo">alert('boo yeah!')</script>
    <img src="https://cdn/blah">
  `))
  if err != nil {
    log.Fatal(err)
  }
  log.Println(valid, reports)
}

License

go-csp-engine is licensed under the MIT license. See LICENSE file for more information.

# Functions

retrieves the current CSP setting from a web page.
ParsePolicy parses all the directives in a CSP policy.
ParseSourceDirective parses a source directive arguments.
ValidatePage checks that an HTML page passes the specified CSP policy.
ValidateStylesheet validates a stylesheet for CSP violations from imports and font-face sources.

# Structs

AllowDirective always allows access to the context.
HashSource is a SourceDirective rule that matches the hash of content.
Policy represents the entire CSP policy and its directives.
Report contains information about a CSP violation.
SourceContext is the context required by a CSP policy.
SourceDirective is used to enforce a CSP source policy on a URL.

# Interfaces

Directive is a rule for a CSP directive.