2019-03-11 16:56:48 +00:00
|
|
|
package nonces
|
2018-12-06 21:50:17 +00:00
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
|
|
|
"fmt"
|
|
|
|
"net/http"
|
|
|
|
"sync"
|
|
|
|
|
2020-09-02 01:20:01 +00:00
|
|
|
"github.com/go-acme/lego/v4/acme/api/internal/sender"
|
2018-12-06 21:50:17 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// Manager Manages nonces.
|
|
|
|
type Manager struct {
|
|
|
|
do *sender.Doer
|
|
|
|
nonceURL string
|
|
|
|
nonces []string
|
|
|
|
sync.Mutex
|
|
|
|
}
|
|
|
|
|
|
|
|
// NewManager Creates a new Manager.
|
|
|
|
func NewManager(do *sender.Doer, nonceURL string) *Manager {
|
|
|
|
return &Manager{
|
|
|
|
do: do,
|
|
|
|
nonceURL: nonceURL,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Pop Pops a nonce.
|
|
|
|
func (n *Manager) Pop() (string, bool) {
|
|
|
|
n.Lock()
|
|
|
|
defer n.Unlock()
|
|
|
|
|
|
|
|
if len(n.nonces) == 0 {
|
|
|
|
return "", false
|
|
|
|
}
|
|
|
|
|
|
|
|
nonce := n.nonces[len(n.nonces)-1]
|
|
|
|
n.nonces = n.nonces[:len(n.nonces)-1]
|
|
|
|
return nonce, true
|
|
|
|
}
|
|
|
|
|
|
|
|
// Push Pushes a nonce.
|
|
|
|
func (n *Manager) Push(nonce string) {
|
|
|
|
n.Lock()
|
|
|
|
defer n.Unlock()
|
|
|
|
n.nonces = append(n.nonces, nonce)
|
|
|
|
}
|
|
|
|
|
2020-05-08 17:35:25 +00:00
|
|
|
// Nonce implement jose.NonceSource.
|
2018-12-06 21:50:17 +00:00
|
|
|
func (n *Manager) Nonce() (string, error) {
|
|
|
|
if nonce, ok := n.Pop(); ok {
|
|
|
|
return nonce, nil
|
|
|
|
}
|
|
|
|
return n.getNonce()
|
|
|
|
}
|
|
|
|
|
|
|
|
func (n *Manager) getNonce() (string, error) {
|
|
|
|
resp, err := n.do.Head(n.nonceURL)
|
|
|
|
if err != nil {
|
2020-03-20 21:53:09 +00:00
|
|
|
return "", fmt.Errorf("failed to get nonce from HTTP HEAD: %w", err)
|
2018-12-06 21:50:17 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return GetFromResponse(resp)
|
|
|
|
}
|
|
|
|
|
|
|
|
// GetFromResponse Extracts a nonce from a HTTP response.
|
|
|
|
func GetFromResponse(resp *http.Response) (string, error) {
|
|
|
|
if resp == nil {
|
|
|
|
return "", errors.New("nil response")
|
|
|
|
}
|
|
|
|
|
|
|
|
nonce := resp.Header.Get("Replay-Nonce")
|
|
|
|
if nonce == "" {
|
2020-02-27 18:14:46 +00:00
|
|
|
return "", errors.New("server did not respond with a proper nonce header")
|
2018-12-06 21:50:17 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return nonce, nil
|
|
|
|
}
|