httpsig

package module
v0.0.0-...-71d3a7e Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 22, 2022 License: BSD-3-Clause Imports: 19 Imported by: 0

README

httpsig

Standards-based HTTP request signing and verification for Go

Go Reference Alpha Quality Build Status BSD license codecov Go Report Card


Introduction

httpsig provides support for signing and verifying HTTP requests according to the HTTP Message Signatures draft standard. This standard focuses on signing headers and request paths, and you probably want to sign the request body too, so body digest calculation according to Digest Headers is included.

Signed HTTP requests are ideal for scenarios like sending webhooks, allowing recievers to securely verify the request came from your server, mitigate replay attacks, etc.

Contrary to the commonly-used x-hub-signature, The standards implemented by this package provide a signature of the entire request, including HTTP headers and the request path.

Usage

Signing HTTP Requests in Clients

To sign HTTP requests from a client, wrap an http.Client's transport with NewSignTransport:

client := http.Client{
	// Wrap the transport:
	Transport: httpsig.NewSignTransport(http.DefaultTransport,
		httpsig.WithSignEcdsaP256Sha256("key1", privKey)),
}

var buf bytes.Buffer

// construct body, etc
// ...

resp, err := client.Post("https://some-url.com", "application/json", &buf)
if err != nil {
	return
}
defer resp.Body.Close()

// ...

Verifying HTTP Requests in Servers

To verify HTTP requests on the server, wrap the http.Handlers you wish to protect with NewVerifyMiddleware. NewVerifyMiddleware returns the wrapping func, so you can reuse configuration across multiple handlers.

h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "text/plain")
	io.WriteString(w, "Your request has an valid signature!")
})

middleware := httpsig.NewVerifyMiddleware(httpsig.WithVerifyEcdsaP256Sha256("key1", pubkey))
http.Handle("/", middleware(h))

For more usage examples and documentation, see the godoc refernce

The Big Feature Matrix

This implementation is based on version 06 of HTTP Message Signatures (draft-ietf-htttpbis-message-signatures-05 from 8 June 2021). Digest computation is based on version 05 of Digest Headers (draft-ietf-httpbis-digest-headers-05 from 13 April 2021).

Feature Notes
sign requests
verify requests
sign responses
verify responses
add expires to signature sorely needed
enforce expires in verify
@method component
@authority component
@scheme component
@target-uri component
@request-target component Semantics changed in draft-06, no longer recommented for use.
@path component
@query component Encoding handling is missing.
@query-params component
@status component
request-response binding
Accept-Signature header
create multiple signatures
verify from multiple signatures
rsa-pss-sha512
rsa-v1_5-sha256
hmac-sha256
ecdsa-p256-sha256
custom signature formats eddsa is not part of the spec, so custom support here would be nice!
JSON Web Signatures JWS doesn't support any additional algs, but it is part of the spec
Signature-Input as trailer Trailers can be dropped. accept for verification only.
Signature as trailer Trailers can be dropped. accept for verification only.
request digests
response digests Tricky to support for signature use according to the spec
multiple digests
digest: sha-256
digest: sha-512
digest: md5 Deprecated in the spec. Unlikely to be supported.
digest: sha Deprecated in the spec. Unlikely to be supported.
digest: unixsum
digest: unixcksum
digest: id-sha-512
digest: id-sha-256 id-* digests are more resilient for content-encoding support
custom digest formats

Contributing

I would love your help!

httpsig is still a work in progress. You can help by:

  • Opening a pull request to resolve an open issue.
  • Adding a feature or enhancement of your own! If it might be big, please open an issue first so we can discuss it.
  • Improving this README or adding other documentation to httpsig.
  • Letting me know if you're using httpsig.

Documentation

Overview

Package httpsig signs and verifies HTTP requests (with body digests) according to the "HTTP Message Signatures" draft standard https://datatracker.ietf.org/doc/draft-ietf-httpbis-message-signatures/

Example (Round_trip)
package main

import (
	"fmt"
	"io"
	"net/http"
	"time"

	"github.com/jbowes/httpsig"
)

const secret = "support-your-local-cat-bonnet-store"

func main() {
	h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "text/plain")
		_, _ = io.WriteString(w, "Your request has a valid signature!")
	})

	middleware := httpsig.NewVerifyMiddleware(httpsig.WithHmacSha256("key1", []byte(secret)))
	http.Handle("/", middleware(h))
	go func() { _ = http.ListenAndServe("127.0.0.1:1234", http.DefaultServeMux) }()

	// Give the server time to sleep. Terrible, I know.
	time.Sleep(100 * time.Millisecond)

	client := http.Client{
		// Wrap the transport:
		Transport: httpsig.NewSignTransport(
			http.DefaultTransport,
			httpsig.HttpSigningConfigs{},
			httpsig.WithHmacSha256("key1", []byte(secret)),
		),
	}

	resp, err := client.Get("http://127.0.0.1:1234/")
	if err != nil {
		fmt.Println("got err: ", err)
		return
	}
	defer resp.Body.Close()

	fmt.Println(resp.Status)

}
Output:

200 OK

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func ContentDigesSHA216

func ContentDigesSHA216(in []byte) string

func NewSignTransport

func NewSignTransport(transport http.RoundTripper, params HttpSigningConfigs, opts ...signOption) http.RoundTripper

NewSignTransport returns a new client transport that wraps the provided transport with http message signing and body digest creation.

Use the various `WithSign*` option funcs to configure signature algorithms with their provided key ids. You must provide at least one signing option. A signature for every provided key id is included on each request. Multiple included signatures allow you to gracefully introduce stronger algorithms, rotate keys, etc.

func NewVerifyMiddleware

func NewVerifyMiddleware(opts ...verifyOption) func(http.Handler) http.Handler

NewVerifyMiddleware returns a configured http server middleware that can be used to wrap multiple handlers for http message signature and digest verification.

Use the `WithVerify*` option funcs to configure signature verification algorithms that map to their provided key ids.

Requests with missing signatures, malformed signature headers, expired signatures, or invalid signatures are rejected with a `400` response. Only one valid signature is required from the known key ids. However, only the first known key id is checked.

func WithHmacSha256

func WithHmacSha256(keyID string, secret []byte) signOrVerifyOption

WithHmacSha256 adds signing or signature verification using `hmac-sha256` with the given shared secret using the given key id.

func WithSignEcdsaP256Sha256

func WithSignEcdsaP256Sha256(keyID string, pk *ecdsa.PrivateKey) signOption

WithSignEcdsaP256Sha256 adds signing using `ecdsa-p256-sha256` with the given private key using the given key id.

func WithSignRSA256

func WithSignRSA256(pk *rsa.PrivateKey) signOption

WithSignEcdsaP256Sha256 adds signing using `ecdsa-p256-sha256` with the given private key using the given key id.

func WithSignRsaPssSha512

func WithSignRsaPssSha512(keyID string, pk *rsa.PrivateKey) signOption

WithSignRsaPssSha512 adds signing using `rsa-pss-sha512` with the given private key using the given key id.

func WithVerifyEcdsaP256Sha256

func WithVerifyEcdsaP256Sha256(keyID string, pk *ecdsa.PublicKey) verifyOption

WithVerifyEcdsaP256Sha256 adds signature verification using `ecdsa-p256-sha256` with the given public key using the given key id.

func WithVerifyRsaPssSha512

func WithVerifyRsaPssSha512(keyID string, pk *rsa.PublicKey) verifyOption

WithVerifyRsaPssSha512 adds signature verification using `rsa-pss-sha512` with the given public key using the given key id.

Types

type HttpSigningConfigs

type HttpSigningConfigs struct {
	// Set of derived components that will be used to sign the outbound message
	// An exaustive list can be found in section 2.2 of the spec
	// Ex: ["@query", "@path", "@method"]
	DerivedComponents map[string]struct{}
	// Set of required HTTP headers that must be present and included in the signature
	// If header is not provided in request this will result in an error before being sent
	Headers map[string]struct{}

	InputHeaderLabel     string
	SignatureHeaderLabel string
	SignatureLabel       string

	PubKey *rsa.PublicKey
}

type Verifier

type Verifier struct {
	SignatureHeaderLabel string
	InputHeaderLabel     string
}

func (Verifier) Verify

func (v Verifier) Verify(httpResp http.Response, pubKey *rsa.PublicKey) error

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL