1
0
mirror of https://github.com/go-acme/lego.git synced 2024-12-23 17:21:50 +02:00
lego/acme/api/internal/nonces/nonce_manager.go
Ludovic Fernandez 3cefc7a51b
chore: fix grammar and typo (#1978)
Co-authored-by: Dominik Menke <git@dmke.org>
2023-07-29 12:59:24 +02:00

79 lines
1.4 KiB
Go

package nonces
import (
"errors"
"fmt"
"net/http"
"sync"
"github.com/go-acme/lego/v4/acme/api/internal/sender"
)
// 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)
}
// Nonce implement jose.NonceSource.
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 {
return "", fmt.Errorf("failed to get nonce from HTTP HEAD: %w", err)
}
return GetFromResponse(resp)
}
// GetFromResponse Extracts a nonce from an 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 == "" {
return "", errors.New("server did not respond with a proper nonce header")
}
return nonce, nil
}