aboutsummaryrefslogtreecommitdiff
path: root/client.go
blob: 596694f10754c3805625038c80fbb96d4ca8f084 (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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
package acme

import (
	"encoding/json"
	"errors"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"regexp"
	"time"
)

// Link to the next stage
type Link map[string]string

// Client ...
type Client struct {
	Dir        Directory
	Link       Link
	Location   string
	nonce      chan string
	RetryAfter time.Duration
}

// NewClient fetches directory and initializes nonce
func NewClient(uri string) (*Client, error) {
	resp, err := http.Get(uri)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	c := &Client{nonce: make(chan string, 10)}
	c.nonce <- replyNonce(resp)
	err = json.NewDecoder(resp.Body).Decode(&c.Dir)
	if err != nil {
		return nil, err
	}
	return c, nil
}

var errNoNonces = errors.New("No nonces available")

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

// Important header fields
//
// Replay-Nonce		each response, required for next request
// Link			links to next stage
// Retry-After		polling interval

// Action		Request		Response
//
// Register		POST new-reg	201 -> reg
// Request challenges	POST new-authz	201 -> authz
// Answer challenges	POST challenge	200
// Poll for status	GET  authz	200
// Request issuance	POST new-cert	201 -> cert
// Check for new cert	GET  cert	200

// request is used for
// new-reg, new-authz, challenge, new-cert
func (c *Client) post(url string, s Signer, v interface{}) error {
	body, err := json.Marshal(v)
	if err != nil {
		return err
	}
	log.Println(string(body))

	signed, err := s.Sign(body, c)
	if err != nil {
		return err
	}

	resp, err := http.Post(url, "application/jose+json", signed)
	if err != nil {
		return err
	}
	defer resp.Body.Close()

	if resp.StatusCode >= http.StatusBadRequest {
		return handleError(resp)
	}

	c.nonce <- replyNonce(resp)
	c.Link = links(resp)
	c.Location = location(resp)

	body, err = ioutil.ReadAll(resp.Body)
	if err != nil {
		return err
	}
	// DEBUG
	log.Println("RESPONSE", string(body))
	return json.Unmarshal(body, v)
	//return json.NewDecoder(resp.Body).Decode(v)
}

func location(r *http.Response) string {
	return r.Header.Get("Location")
}

func links(r *http.Response) Link {
	link := make(Link)
	reg := regexp.MustCompile(`^<(.*)>;rel="(.*)"`)
	for _, l := range r.Header["Link"] {
		re := reg.FindStringSubmatch(l)
		if len(re) == 3 {
			link[re[2]] = re[1]
		}
	}
	return link
}

func retryAfter(r *http.Response) time.Duration {
	ra := r.Header.Get("Retry-After")
	if d, err := time.ParseDuration(ra + "s"); err == nil {
		return d
	}
	return time.Second
}

func replyNonce(r *http.Response) string {
	return r.Header.Get("Replay-Nonce")
}

/*
                              directory
                                  .
                                  .
      ....................................................
      .                  .                  .            .
      .                  .                  .            .
      V     "next"       V      "next"      V            V
   new-reg ---+----> new-authz ---+----> new-cert    revoke-cert
      .       |          .        |         .            ^
      .       |          .        |         .            | "revoke"
      V       |          V        |         V            |
     reg* ----+        authz -----+       cert-----------+
                        . ^                 |
                        . | "up"            | "up"
                        V |                 V
                      challenge         cert-chain
*/

func (c *Client) Register(a *Account) (*Registration, error) {
	r := &Registration{
		Resource: ResNewReg,
		Contact:  a.Contact,
	}
	err := c.post(c.Dir.NewReg, a, r)
	return r, err
}

// Agree to TOS
func (c *Client) Agree(a *Account) (*Registration, error) {
	r := &Registration{
		Resource:  ResRegister,
		Contact:   a.Contact,
		Agreement: c.Link["terms-of-service"],
	}
	err := c.post(c.Location, a, r)
	return r, err
}

func (c *Client) Authorize(a *Account, domain string) (*Authorization, error) {
	r := &Authorization{
		Resource: ResNewAuthz,
		Identifier: Identifier{
			Type:  IdentDNS,
			Value: domain,
		},
	}
	err := c.post(c.Dir.NewAuthz, a, r)
	return r, err
}

func (c Client) String() string {
	return fmt.Sprintf("Link: %v, Location: %v", c.Link, c.Location)
}