aboutsummaryrefslogtreecommitdiff
path: root/signer.go
blob: 3eb25fc562958db567263f50cae44315429485de (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package acme

import (
	"crypto"
	"crypto/ecdsa"
	"crypto/rsa"
	"encoding/base64"
	"errors"
	"io/ioutil"
	"net/http"
	"strings"

	"github.com/square/go-jose"
)

// KeySize is a default RSA key size
const KeySize = 2048

var errNoNonces = errors.New("out of nonces")

// Signer ...
type Signer struct {
	jose.Signer
	nonces chan string
}

func thumb(pubKey crypto.PublicKey) (string, error) {
	jwk := &jose.JsonWebKey{Key: pubKey}
	t, err := jwk.Thumbprint(crypto.SHA256)
	return base64.RawURLEncoding.EncodeToString(t), err
}

func Thumb(privKey crypto.PrivateKey) (string, error) {
	switch k := privKey.(type) {
	case *rsa.PrivateKey:
		return thumb(k.Public())
	case *ecdsa.PrivateKey:
		return thumb(k.Public())
	}
	return "", ErrKeyType
}

func NewSigner(privKey crypto.PrivateKey) (*Signer, error) {
	switch k := privKey.(type) {
	case *rsa.PrivateKey:
		s, err := jose.NewSigner(jose.RS256, k)
		if err != nil {
			return nil, err
		}
		sig := &Signer{Signer: s, nonces: make(chan string, 100)}
		sig.SetNonceSource(sig)
		return sig, nil
	case *ecdsa.PrivateKey:
		s, err := jose.NewSigner(jose.ES384, k)
		if err != nil {
			return nil, err
		}
		sig := &Signer{Signer: s, nonces: make(chan string, 100)}
		sig.SetNonceSource(sig)
		return sig, nil
	default:
		return nil, ErrKeyType
	}
}

// Nonce implements jose nonce provider
func (s Signer) Nonce() (string, error) {
	select {
	case nonce := <-s.nonces:
		return nonce, nil
	default:
		return "", errNoNonces
	}
}

// RoundTrip extracts nonces from HTTP response
func (s Signer) RoundTrip(req *http.Request) (*http.Response, error) {
	if req.Method == http.MethodPost {
		body, err := ioutil.ReadAll(req.Body)
		if err != nil {
			return nil, err
		}
		req.Body.Close()
		obj, err := s.Sign(body)
		if err != nil {
			return nil, err
		}
		signed := obj.FullSerialize()
		req.ContentLength = int64(len(signed))
		req.Body = ioutil.NopCloser(strings.NewReader(signed))
	}
	resp, err := http.DefaultTransport.RoundTrip(req)
	if err != nil {
		return nil, err
	}
	if nonce := resp.Header.Get("Replay-Nonce"); nonce != "" {
		if len(s.nonces) == cap(s.nonces) {
			<-s.nonces // drop oldest
		}
		s.nonces <- nonce
	}
	return resp, nil
}