ACME2.pm untested

filter: Statementstmt 0.0% 0 / 128 Branchbran 0.0% 0 / 22 Conditioncond 0.0% 0 / 26 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 29 Podpod 0.0% 0 / 17 totaltotal 0.0% 0 / 222 CC 12 SCAR 17.5
CC
12
Cov
0%
create_new_account
20.0
_poll_order_or_authz
12.0
new
6.0
CRAP 5.8
1 package Net::ACME2;
2  
3 use strict;
4 use warnings;
5  
6 =encoding utf-8
7  
8 =head1 NAME
9  
10 Net::ACME2 - L<IETF|https://www.ietf.org>-standard ACME (Let’s Encrypt) client
11  
12 X<Lets Encrypt> X<Let's Encrypt> X<letsencrypt>
13  
14 =head1 SYNOPSIS
15  
16 package SomeCA::ACME;
17  
18 use parent qw( Net::ACME2 );
19  
20 use constant {
21 HOST => 'acme.someca.net',
22 DIRECTORY_PATH => '/acme-directory',
23 };
24  
25 package main;
26  
27 my $acme = SomeCA::ACME->new(
28 key => $account_key_pem_or_der,
29 key_id => undef,
30 );
31  
32 #for a new account
33 {
34 my $terms_url = $acme->get_terms_of_service();
35  
36 $acme->create_new_account(
37 termsOfServiceAgreed => 1,
38 );
39 }
40  
41 #Save $acme->key_id() somewhere so you can use it again.
42  
43 my $order = $acme->create_new_order(
44 identifiers => [
45 { type => 'dns', value => '*.example.com' },
46 ],
47 );
48  
49 my $authz = $acme->get_authorization( ($order->authorizations())[0] );
50  
51 my @challenges = $authz->challenges();
52  
53 # ... Pick a challenge, and satisfy it.
54  
55 $acme->accept_challenge($challenge);
56  
57 sleep 1 while !$acme->poll_authorization($authz);
58  
59 # ... Make a key and CSR for *.example.com
60  
61 $acme->finalize_order($order, $csr_pem_or_der);
62  
63 while ($order->status() ne 'valid') {
64 sleep 1;
65 $acme->poll_order($order);
66 }
67  
68 my $certificate_url = $order->certificate();
69  
70 # ... Download your certificate! :)
71  
72 See F</examples> in the distribution for a more fleshed-out example.
73  
74 To use L<Let’s Encrypt|http://letsencrypt.org>, see
75 L<Net::ACME2::LetsEncrypt>.
76  
77 =head1 DESCRIPTION
78  
79 This library implements client logic for the L<IETF|https://www.ietf.org>-standard ACME
80 (Automated Certificate Management Environment) protocol. As of this
81 writing, that protocol remains in development; the latest draft will
82 be available from L<https://datatracker.ietf.org/doc/draft-ietf-acme-acme/>.
83  
84 Net::ACME2 derives from L<Net::ACME>, which implements the
85 (significantly different) earlier draft of that protocol as initially
86 deployed by L<Let’s Encrypt|http://letsencrypt.org>.
87  
88 Net::ACME2 is pure Perl, and all of its dependencies are either pure Perl
89 or core modules.
90  
91 =head1 STATUS
92  
93 This is an alpha-grade implementation. While the underlying protocol
94 is L<in use for production|https://community.letsencrypt.org/t/acme-v2-production-environment-wildcards/55578>,
95 it’s still not finalized; consequently, this distribution remains
96 subject to change.
97  
98 =head1 FEATURES
99  
100 =over
101  
102 =item * This is a pure-Perl solution, all of whose dependencies are either
103 core modules or pure-Perl themselves. Net::ACME2 will run anywhere that Perl
104 runs. :)
105  
106 =item * Support for both ECDSA and RSA encrytion.
107  
108 =item * Comprehensive error handling with typed, L<X::Tiny>-based exceptions.
109  
110 =back
111  
112 =head1 ERROR HANDLING
113  
114 All thrown exceptions are instances of L<Net::ACME2::X::Base>.
115 Specific error classes aren’t yet defined.
116  
117 =cut
118  
119 use Crypt::Format ();
120 use MIME::Base64 ();
121  
122 use Net::ACME2::Constants ();
123 use Net::ACME2::HTTP ();
124 use Net::ACME2::Order ();
125 use Net::ACME2::Authorization ();
126  
127 our $VERSION;
128 *VERSION = *Net::ACME2::Constants::VERSION;
129  
130 use constant {
131 JWS_FORMAT => undef,
132  
133 _JWK_THUMBPRINT_DIGEST => 'sha256',
134 };
135  
136 use constant newAccount_booleans => qw(
137 termsOfServiceAgreed
138 onlyReturnExisting
139 );
140  
141 use constant FULL_JWT_METHODS => qw(
142 newAccount
143 revokeCert
144 );
145  
146 =head1 METHODS
147  
148 =head2 I<CLASS>->new( %OPTS )
149  
150 Instantiates an ACME2 object, which you’ll use for all
151 interactions with the ACME server. %OPTS is:
152  
153 =over
154  
155 =item * C<key> - Required. The private key to associate with the ACME2
156 user. PEM or DER format.
157  
158 =item * C<key_id> - Optional. As returned by C<key_id()>.
159 Saves a round-trip to the ACME2 server, so you should give this
160 if you have it.
161  
162 =item * C<directory> - Optional. A hash reference to use as the
163 directory contents. Saves a round-trip to the ACME2 server, but there’s
164 no built-in logic to determine when the cache goes invalid. Caveat
165 emptor.
166  
167 =back
168  
169 =cut
170  
171 sub new {
172 my ( $class, %opts ) = @_;
173  
174 die 'Need “key”!' if !$opts{'key'};
175  
176 my $self = {
177 _host => $class->HOST(),
178 _key => $opts{'key'},
179 _key_id => $opts{'key_id'},
180 _directory => $opts{'directory'},
181 };
182  
183 bless $self, $class;
184  
185 $self->_set_ua();
186  
187 return $self;
188 }
189  
190 =head2 I<OBJ>->key_id()
191  
192 Returns the object’s cached key ID, either as given at instantiation
193 or as fetched in C<create_new_account()>.
194  
195 =cut
196  
197 sub key_id {
198 my ($self) = @_;
199  
200 return $self->{'_key_id'};
201 }
202  
203 =head2 I<CLASS_OR_OBJ>->get_terms_of_service()
204  
205 Callable as either an instance method or a class method.
206 Returns the URL for the terms of service.
207  
208 B<NOTE:> For L<Let’s Encrypt|http://letsencrypt.org> you can
209 unofficially resolve against
210 L<https://acme-v01.api.letsencrypt.org/terms> to see the terms
211 of service.
212  
213 =cut
214  
215 sub get_terms_of_service {
216 my ($self) = @_;
217  
218 #We want to be able to call this as a class method.
219 if (!ref $self) {
220 $self = $self->new();
221 }
222  
223 my $dir = $self->_get_directory();
224 my $url = $self->_get_directory()->{'meta'} or die 'No “meta” in directory!';
225 $url = $url->{'termsOfService'} or die 'No “terms-of-service” in directory metadata!';
226  
227 return $url;
228 }
229  
230 =head2 I<OBJ>->create_new_account( %OPTS )
231  
232 Creates a new account using the ACME2 object’s key and the passed
233 %OPTS, which are as described in the ACME2 spec (cf. C<newAccount>).
234 Boolean values may be given as simple Perl booleans.
235  
236 Returns 1 if the account is newly created
237 or 0 if the account already existed.
238  
239 =cut
240  
241 sub create_new_account {
242 my ($self, %opts) = @_;
243  
244 $opts{$_} &&= JSON::true() for newAccount_booleans();
245  
246 my $resp = $self->_post(
247 'newAccount',
248 \%opts,
249 );
250  
251 $self->{'_key_id'} = $resp->header('location');
252  
253 $self->{'_ua'}->set_key_id( $self->{'_key_id'} );
254  
255 return 0 if $resp->status() == 200;
256  
257 $resp->die_because_unexpected() if $resp->status() != 201;
258  
259 my $struct = $resp->content_struct();
260  
261 if ($struct) {
262 $struct->{$_} = !!$struct->{$_} for newAccount_booleans();
263 }
264  
265 return 1;
266 }
267  
268 #sub update_account {
269 # my ($self, %opts) = @_;
270 #
271 # $self->_require_key_id(\%opts);
272 #
273 # my $set = $self->_post_url(
274 # $opts{'kid'},
275 # \%opts,
276 # );
277 #
278 # return $set;
279 #}
280  
281 =head2 I<OBJ>->create_new_order( %OPTS )
282  
283 Returns a L<Net::ACME2::Order> object. %OPTS is as described in the
284 ACME spec (cf. C<newOrder>). Boolean values may be given as simple
285 Perl booleans.
286  
287 =cut
288  
289 sub create_new_order {
290 my ($self, %opts) = @_;
291  
292 $self->_require_key_id(\%opts);
293  
294 my $resp = $self->_post( 'newOrder', \%opts );
295  
296 $resp->die_because_unexpected() if $resp->status() != 201;
297  
298 return Net::ACME2::Order->new(
299 id => $resp->header('location'),
300 %{ $resp->content_struct() },
301 );
302 }
303  
304 =head2 I<OBJ>->get_authorization( URL )
305  
306 Fetches the authorization’s information based on the given URL
307 and returns a L<Net::ACME2::Authorization> object.
308  
309 The URL is as given by L<Net::ACME2::Order>.
310  
311 =cut
312  
313 sub get_authorization {
314 my ($self, $id) = @_;
315  
316 my $resp = $self->{'_ua'}->get($id);
317  
318 return Net::ACME2::Authorization->new(
319 id => $id,
320 %{ $resp->content_struct() },
321 );
322 }
323  
324 #Server may not support! (Pebble doesn’t, and LE won’t?)
325 #sub create_new_authorization {
326 # my ($self, $type, $value) = @_;
327 #
328 # my %opts = (
329 # identifier => { type => $type, value => $value },
330 # );
331 #
332 # $self->_require_key_id(\%opts);
333 #
334 # return $self->_post( 'newAuthz', \%opts );
335 #}
336  
337 #TODO: separate distribution?
338 #sub __unix2iso {
339 # my ($unix) = @_;
340 #
341 # my (@smhdmy) = gmtime $unix;
342 # $smhdmy[5] += 1900;
343 # $smhdmy[4]++;
344 #
345 # return join( q<>,
346 # join( '-', @smhdmy[ 5, 4, 3 ] ),
347 # 'T',
348 # join( ':', @smhdmy[ 2, 1, 0 ] ),
349 # 'Z',
350 # );
351 #}
352  
353 =head2 I<OBJ>->make_key_authorization( CHALLENGE )
354  
355 Accepts an instance of L<Net::ACME2::Challenge> (probably a subclass
356 thereof) and returns
357 a key authorization string suitable for handling the given CHALLENGE.
358 See F</examples> in the distribution for example usage.
359  
360 If you’re using HTTP authorization and are on the same server as the
361 domains’ document roots, then look at the handler logic in
362 L<Net::ACME2::Challenge::http_01> for a potentially simpler way to
363 handle HTTP challenges.
364  
365 =cut
366  
367 sub make_key_authorization {
368 my ($self, $challenge_obj) = @_;
369  
370 die 'Need a challenge object!' if !$challenge_obj;
371  
372 return $challenge_obj->token() . '.' . $self->_key_thumbprint();
373 }
374  
375 =head2 I<OBJ>->accept_challenge( CHALLENGE )
376  
377 Signal to the ACME server that the CHALLENGE is ready.
378  
379 =cut
380  
381 sub accept_challenge {
382 my ($self, $challenge_obj) = @_;
383  
384 my $post = $self->_post_url(
385 $challenge_obj->url(),
386 {
387 keyAuthorization => $self->make_key_authorization($challenge_obj),
388 },
389 );
390  
391 return;
392 }
393  
394 =head2 I<OBJ>->poll_authorization( AUTHORIZATION )
395  
396 Accepts a L<Net::ACME2::Authorization> instance and polls the
397 ACME server for that authorization’s status. The AUTHORIZATION
398 object is then updated with the results of the poll.
399  
400 =cut
401  
402 #This has to handle updates to the authz and challenge objects
403 *poll_authorization = *_poll_order_or_authz;
404  
405 =head2 I<OBJ>->finalize_order( ORDER, CSR )
406  
407 Finalizes an order and updates the ORDER object with the returned
408 status. The CSR may be in either DER or PEM format.
409  
410 ORDER may have C<status()> of C<valid> after this operation,
411 or you may need to C<poll_order()>.
412  
413 =cut
414  
415 sub finalize_order {
416 my ($self, $order_obj, $csr) = @_;
417  
418 my $csr_der;
419 if (index($csr, '-----') == 0) {
420 $csr_der = Crypt::Format::pem2der($csr);
421 }
422 else {
423 $csr_der = $csr;
424 }
425  
426 $csr = MIME::Base64::encode_base64url($csr_der);
427  
428 my $post = $self->_post_url(
429 $order_obj->finalize(),
430 {
431 csr => $csr,
432 },
433 );
434  
435 my $content = $post->content_struct();
436  
437 $order_obj->update($content);
438  
439 return;
440 }
441  
442 =head2 I<OBJ>->poll_order( ORDER )
443  
444 Like C<poll_authorization()> but handles a
445 L<Net::ACME2::Order> object instead.
446  
447 =cut
448  
449 *poll_order = *_poll_order_or_authz;
450  
451 #----------------------------------------------------------------------
452  
453 sub _key_thumbprint {
454 my ($self) = @_;
455  
456 return $self->{'_key_thumbprint'} ||= $self->_key_obj()->get_jwk_thumbprint( _JWK_THUMBPRINT_DIGEST() );
457 }
458  
459 sub _get_directory {
460 my ($self) = @_;
461  
462 $self->{'_directory'} ||= do {
463 my $dir_path = $self->DIRECTORY_PATH();
464 $self->{'_ua'}->get("https://$self->{'_host'}$dir_path")->content_struct();
465 };
466  
467 $self->{'_ua'}->set_new_nonce_url( $self->{'_directory'}{'newNonce'} );
468  
469 return $self->{'_directory'};
470 }
471  
472 sub _require_key_id {
473 my ($self, $opts_hr) = @_;
474  
475 $opts_hr->{'_key_id'} = $self->{'_key_id'} or do {
476 die 'No key ID has been set. Either pass “key_id” to new(), or create_new_account().';
477 };
478  
479 return
480 }
481  
482 sub _poll_order_or_authz {
483 my ($self, $order_or_authz_obj) = @_;
484  
485 my $get = $self->{'_ua'}->get( $order_or_authz_obj->id() );
486  
487 my $content = $get->content_struct();
488  
489 $order_or_authz_obj->update($content);
490  
491 my $status = $order_or_authz_obj->status();
492  
493 return 1 if $status eq 'valid';
494 return 0 if $status eq 'pending' || $status eq 'processing';
495  
496 use Data::Dumper;
497 die Dumper $order_or_authz_obj; #TODO
498 }
499  
500 sub _key_obj {
501 my ($self) = @_;
502  
503 return $self->{'_key_obj'} ||= Crypt::Perl::PK::parse_key($self->{'_key'});
504 }
505  
506 sub _set_ua {
507 my ($self) = @_;
508  
509 $self->{'_ua'} = Net::ACME2::HTTP->new(
510 key => $self->_key_obj(),
511 key_id => $self->{'_key_id'},
512 jws_format => $self->JWS_FORMAT(),
513 );
514  
515 return;
516 }
517  
518 our $_POST_METHOD;
519  
520 sub _post {
521 my ( $self, $link_name, $data ) = @_;
522  
523 my $post_method;
524 $post_method = 'post_full_jwt' if grep { $link_name eq $_ } FULL_JWT_METHODS();
525  
526 my $url = $self->_get_directory()->{$link_name} or die "Unknown link name: “$link_name”";
527  
528 return $self->_post_url( $url, $data, $post_method );
529 }
530  
531 sub _post_url {
532 my ( $self, $url, $data, $opt_post_method ) = @_;
533  
534 #Do this in case we haven’t initialized the directory yet.
535 #Initializing the directory is necessary to get a nonce.
536 $self->_get_directory();
537  
538 my $post_method = $opt_post_method || 'post_key_id';
539  
540 return $self->{'_ua'}->$post_method( $url, $data );
541 }
542  
543 1;
544  
545 =head1 TODO
546  
547 =over
548  
549 =item * Add pre-authorization support if there is ever a production
550 use for it.
551  
552 =item * Tighten up challenge failure response.
553  
554 =item * Add (more) tests.
555  
556 =back
557  
558 =head1 SEE ALSO
559  
560 L<Crypt::Perl> provides pure-Perl cryptography for this library. See the
561 present library distribution’s F</examples> directory for sample usage
562 to generate keys and CSRs.
563  
564 =cut