aboutsummaryrefslogtreecommitdiff
path: root/provider.go
blob: f671c326ff9b22eab955f479da97ac07ba30592f (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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
package acme

import (
	"crypto/x509"
	"encoding/json"
	"errors"
	"log"
	"net/http"
	"regexp"
	"time"
)

// Provider ...
type Provider struct {
	Directory
	nonces chan string
	http.Client
	http.Transport
	poll time.Duration
}

var (
	errNoNonces    = errors.New("out of nonces")
	errContentType = errors.New("unknown content type")
	errChalType    = errors.New("unknown challenge")
	errStatus      = errors.New("unexpected status")
)

const (
	mimeJson    = "application/json"
	mimeJose    = "application/jose+json"
	mimeProblem = "application/problem+json"
	mimePkix    = "application/pkix-cert"
)

// RoundTrip implements RoundTipper
func (p Provider) RoundTrip(req *http.Request) (*http.Response, error) {
	resp, err := p.Transport.RoundTrip(req)
	if err != nil {
		return nil, err
	}
	if nonce := resp.Header.Get("Replay-Nonce"); nonce != "" {
		if len(p.nonces) == cap(p.nonces) {
			<-p.nonces // drop oldest
		}
		p.nonces <- nonce
	}
	// not sure if it belongs here
	if resp.Header.Get("Content-Type") == mimeProblem {
		defer resp.Body.Close()
		return nil, problem(resp.Body)
	}
	return resp, nil
}

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

// DialProvider fetches directory and initializes nonce
func DialProvider(directory string) (*Provider, error) {
	p := &Provider{
		nonces: make(chan string, 3),
		poll:   time.Second,
	}
	p.Client = http.Client{
		Transport: p,
		Timeout:   time.Duration(5 * time.Second),
	}
	resp, err := p.Get(directory)
	if err != nil {
		return nil, err
	}
	return p, parseJson(resp, &p.Directory)
}

func (p *Provider) post(uri string, s Signer, v interface{}) (*http.Response, error) {
	msg, err := json.Marshal(v)
	if err != nil {
		return nil, err
	}
	signed, err := s.Sign(msg, p)
	if err != nil {
		return nil, err
	}
	return p.Post(uri, mimeJose, signed)
}

type nextStep struct {
	Link     map[string]string
	Location string
}

var linksRe = regexp.MustCompile(`^<(.*)>;rel="(.*)"`)

func parseHeader(resp *http.Response) nextStep {
	var ns nextStep
	if lo, _ := resp.Location(); lo != nil {
		ns.Location = lo.String()
	}
	ns.Link = make(map[string]string)
	for _, li := range resp.Header["Link"] {
		re := linksRe.FindStringSubmatch(li)
		if len(re) == 3 {
			ns.Link[re[2]] = re[1]
		}
	}
	return ns
}

func parseJson(resp *http.Response, v interface{}) error {
	defer resp.Body.Close()
	if resp.Header.Get("Content-Type") != mimeJson {
		return errContentType
	}
	return json.NewDecoder(resp.Body).Decode(v)
}

func parseCert(resp *http.Response) (*x509.Certificate, error) {
	defer resp.Body.Close()
	if resp.Header.Get("Content-Type") != mimePkix {
		return nil, errContentType
	}
	return readCert(resp.Body)
}

func (p *Provider) Register(s Signer, c Contacts) error {
	// first step: new-reg
	r := &Registration{
		Resource: ResNewReg,
		Contact:  c,
	}
	resp, err := p.post(p.NewReg, s, r)
	if err != nil && err.(Problem).Err != ErrMalformed {
		return err
	}
	ns := parseHeader(resp)

	// second step: reg, agree to tos
	r = &Registration{
		Resource:  ResReg,
		Agreement: ns.Link["terms-of-service"],
	}
	resp, err = p.post(ns.Location, s, r)
	if err != nil {
		return err
	}
	resp.Body.Close()
	return nil
}

func (p *Provider) solve(s Signer, ch Challenge) error {
	ka, err := s.KeyAuth(ch.Token)
	if err != nil {
		return err
	}

	log.Println("prevare solver", ch.Type)
	err = ch.Solve(ch.Token, ka)
	if err != nil {
		return err
	}

	log.Println("poke solver", ch.Type)
	r := &Challenge{
		Resource:         ResChallenge,
		Type:             ch.Type,
		KeyAuthorization: ka,
	}
	resp, err := p.post(ch.URI, s, r)
	if err != nil {
		return err
	}
	ns := parseHeader(resp)

	log.Println("start polling")
	t := time.NewTicker(p.poll)
	defer t.Stop()
	for range t.C {
		done, err := p.queryStatus(ns.Location)
		if err != nil {
			return err
		}
		if done {
			break
		}
	}
	return ch.Solved()
}

func (p *Provider) authz(s Signer, domain string, sol map[ChalType]Solver) error {
	// first step: pocke
	r := &Authorization{
		Resource: ResNewAuthz,
		Identifier: Identifier{
			Type:  IdentDNS,
			Value: domain,
		},
	}
	resp, err := p.post(p.NewAuthz, s, r)
	if err != nil {
		return err
	}
	err = parseJson(resp, r)
	if err != nil {
		return err
	}
	// second step: choose and start solver
	for _, ch := range r.Supported(sol) {
		if err = p.solve(s, ch); err != nil {
			return err
		}
	}
	return nil
}

func (p *Provider) Authz(s Signer, d *Desire) error {
	for _, domain := range d.altnames {
		if err := p.authz(s, domain, d.solver); err != nil {
			return err
		}
	}
	return nil
}

func (p *Provider) queryStatus(uri string) (bool, error) {
	resp, err := p.Get(uri)
	if err != nil {
		return false, err
	}
	r := new(Challenge)
	err = parseJson(resp, r)
	if err != nil {
		return false, err
	}
	log.Println("status", r.Status)
	if r.Err != nil {
		return false, r.Err
	}
	return r.Status == StatusValid, nil
}

func (p *Provider) Bundle(s Signer, d *Desire) error {
	// first step: post csr
	csr, err := d.CSR()
	if err != nil {
		return err
	}
	r := &CSR{
		Resource: ResNewCert,
		CSR:      csr,
	}
	resp, err := p.post(p.NewCert, s, r)
	if err != nil {
		return err
	}
	crt, err := parseCert(resp)
	if err != nil {
		return err
	}
	d.cert = append(d.cert, crt)
	ns := parseHeader(resp)

	// second step: cet CA
	resp, err = p.Get(ns.Link["up"])
	if err != nil {
		return err
	}
	crt, err = parseCert(resp)
	if err != nil {
		return err
	}
	d.cert = append(d.cert, crt)

	return nil
}