File: nonce_manager.go

package info (click to toggle)
golang-github-xenolf-lego 4.9.1-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 5,080 kB
  • sloc: xml: 533; makefile: 128; sh: 18
file content (78 lines) | stat: -rw-r--r-- 1,480 bytes parent folder | download | duplicates (2)
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
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 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 == "" {
		return "", errors.New("server did not respond with a proper nonce header")
	}

	return nonce, nil
}