001/* 002 * acme4j - Java ACME client 003 * 004 * Copyright (C) 2023 Richard "Shred" Körber 005 * http://acme4j.shredzone.org 006 * 007 * Licensed under the Apache License, Version 2.0 (the "License"); 008 * you may not use this file except in compliance with the License. 009 * 010 * This program is distributed in the hope that it will be useful, 011 * but WITHOUT ANY WARRANTY; without even the implied warranty of 012 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 013 */ 014package org.shredzone.acme4j.connector; 015 016import static java.time.format.DateTimeFormatter.RFC_1123_DATE_TIME; 017import static java.util.function.Predicate.not; 018 019import java.io.IOException; 020import java.io.InputStream; 021import java.net.MalformedURLException; 022import java.net.URI; 023import java.net.URL; 024import java.net.http.HttpClient; 025import java.net.http.HttpRequest; 026import java.net.http.HttpResponse; 027import java.security.KeyPair; 028import java.security.cert.CertificateException; 029import java.security.cert.CertificateFactory; 030import java.security.cert.X509Certificate; 031import java.time.Instant; 032import java.time.ZoneId; 033import java.time.ZonedDateTime; 034import java.time.format.DateTimeParseException; 035import java.util.Collection; 036import java.util.List; 037import java.util.Objects; 038import java.util.Optional; 039import java.util.Set; 040import java.util.function.Consumer; 041import java.util.regex.Matcher; 042import java.util.regex.Pattern; 043import java.util.zip.GZIPInputStream; 044 045import edu.umd.cs.findbugs.annotations.Nullable; 046import org.shredzone.acme4j.Login; 047import org.shredzone.acme4j.Problem; 048import org.shredzone.acme4j.Session; 049import org.shredzone.acme4j.exception.AcmeException; 050import org.shredzone.acme4j.exception.AcmeNetworkException; 051import org.shredzone.acme4j.exception.AcmeProtocolException; 052import org.shredzone.acme4j.exception.AcmeRateLimitedException; 053import org.shredzone.acme4j.exception.AcmeServerException; 054import org.shredzone.acme4j.exception.AcmeUnauthorizedException; 055import org.shredzone.acme4j.exception.AcmeUserActionRequiredException; 056import org.shredzone.acme4j.toolbox.AcmeUtils; 057import org.shredzone.acme4j.toolbox.JSON; 058import org.shredzone.acme4j.toolbox.JSONBuilder; 059import org.shredzone.acme4j.toolbox.JoseUtils; 060import org.slf4j.Logger; 061import org.slf4j.LoggerFactory; 062 063/** 064 * Default implementation of {@link Connection}. It communicates with the ACME server via 065 * HTTP, with a client that is provided by the given {@link HttpConnector}. 066 */ 067public class DefaultConnection implements Connection { 068 private static final Logger LOG = LoggerFactory.getLogger(DefaultConnection.class); 069 070 private static final int HTTP_OK = 200; 071 private static final int HTTP_CREATED = 201; 072 private static final int HTTP_NO_CONTENT = 204; 073 private static final int HTTP_NOT_MODIFIED = 304; 074 075 private static final String ACCEPT_HEADER = "Accept"; 076 private static final String ACCEPT_CHARSET_HEADER = "Accept-Charset"; 077 private static final String ACCEPT_LANGUAGE_HEADER = "Accept-Language"; 078 private static final String ACCEPT_ENCODING_HEADER = "Accept-Encoding"; 079 private static final String CACHE_CONTROL_HEADER = "Cache-Control"; 080 private static final String CONTENT_TYPE_HEADER = "Content-Type"; 081 private static final String DATE_HEADER = "Date"; 082 private static final String EXPIRES_HEADER = "Expires"; 083 private static final String IF_MODIFIED_SINCE_HEADER = "If-Modified-Since"; 084 private static final String LAST_MODIFIED_HEADER = "Last-Modified"; 085 private static final String LINK_HEADER = "Link"; 086 private static final String LOCATION_HEADER = "Location"; 087 private static final String REPLAY_NONCE_HEADER = "Replay-Nonce"; 088 private static final String RETRY_AFTER_HEADER = "Retry-After"; 089 private static final String DEFAULT_CHARSET = "utf-8"; 090 private static final String MIME_JSON = "application/json"; 091 private static final String MIME_JSON_PROBLEM = "application/problem+json"; 092 private static final String MIME_CERTIFICATE_CHAIN = "application/pem-certificate-chain"; 093 094 private static final URI BAD_NONCE_ERROR = URI.create("urn:ietf:params:acme:error:badNonce"); 095 private static final int MAX_ATTEMPTS = 10; 096 097 private static final Pattern NO_CACHE_PATTERN = Pattern.compile("(?:^|.*?,)\\s*no-(?:cache|store)\\s*(?:,.*|$)", Pattern.CASE_INSENSITIVE); 098 private static final Pattern MAX_AGE_PATTERN = Pattern.compile("(?:^|.*?,)\\s*max-age=(\\d+)\\s*(?:,.*|$)", Pattern.CASE_INSENSITIVE); 099 private static final Pattern DIGITS_ONLY_PATTERN = Pattern.compile("^\\d+$"); 100 101 protected final HttpConnector httpConnector; 102 protected final HttpClient httpClient; 103 protected @Nullable HttpResponse<InputStream> lastResponse; 104 105 /** 106 * Creates a new {@link DefaultConnection}. 107 * 108 * @param httpConnector 109 * {@link HttpConnector} to be used for HTTP connections 110 */ 111 public DefaultConnection(HttpConnector httpConnector) { 112 this.httpConnector = Objects.requireNonNull(httpConnector, "httpConnector"); 113 this.httpClient = httpConnector.getHttpClient(); 114 } 115 116 @Override 117 public void resetNonce(Session session) throws AcmeException { 118 assertConnectionIsClosed(); 119 120 try (var nonceHolder = session.lockNonce()) { 121 nonceHolder.setNonce(null); 122 123 var newNonceUrl = session.resourceUrl(Resource.NEW_NONCE); 124 125 LOG.debug("HEAD {}", newNonceUrl); 126 127 sendRequest(session, newNonceUrl, b -> 128 b.method("HEAD", HttpRequest.BodyPublishers.noBody())); 129 130 logHeaders(); 131 132 var rc = getResponse().statusCode(); 133 if (rc != HTTP_OK && rc != HTTP_NO_CONTENT) { 134 throw new AcmeException("Server responded with HTTP " + rc + " while trying to retrieve a nonce"); 135 } 136 137 nonceHolder.setNonce(getNonce() 138 .orElseThrow(() -> new AcmeProtocolException("Server did not provide a nonce")) 139 ); 140 } catch (IOException ex) { 141 throw new AcmeNetworkException(ex); 142 } finally { 143 close(); 144 } 145 } 146 147 @Override 148 public int sendRequest(URL url, Session session, @Nullable ZonedDateTime ifModifiedSince) 149 throws AcmeException { 150 Objects.requireNonNull(url, "url"); 151 Objects.requireNonNull(session, "session"); 152 assertConnectionIsClosed(); 153 154 LOG.debug("GET {}", url); 155 156 try (var nonceHolder = session.lockNonce()) { 157 sendRequest(session, url, builder -> { 158 builder.GET(); 159 builder.header(ACCEPT_HEADER, MIME_JSON); 160 if (ifModifiedSince != null) { 161 builder.header(IF_MODIFIED_SINCE_HEADER, ifModifiedSince.format(RFC_1123_DATE_TIME)); 162 } 163 }); 164 165 logHeaders(); 166 167 getNonce().ifPresent(nonceHolder::setNonce); 168 169 var rc = getResponse().statusCode(); 170 if (rc != HTTP_OK && rc != HTTP_CREATED && (rc != HTTP_NOT_MODIFIED || ifModifiedSince == null)) { 171 throwAcmeException(); 172 } 173 return rc; 174 } catch (IOException ex) { 175 throw new AcmeNetworkException(ex); 176 } 177 } 178 179 @Override 180 public int sendCertificateRequest(URL url, Login login) throws AcmeException { 181 return sendSignedRequest(url, null, login.getSession(), login.getKeyPair(), 182 login.getAccountLocation(), MIME_CERTIFICATE_CHAIN); 183 } 184 185 @Override 186 public int sendSignedPostAsGetRequest(URL url, Login login) throws AcmeException { 187 return sendSignedRequest(url, null, login.getSession(), login.getKeyPair(), 188 login.getAccountLocation(), MIME_JSON); 189 } 190 191 @Override 192 public int sendSignedRequest(URL url, JSONBuilder claims, Login login) throws AcmeException { 193 return sendSignedRequest(url, claims, login.getSession(), login.getKeyPair(), 194 login.getAccountLocation(), MIME_JSON); 195 } 196 197 @Override 198 public int sendSignedRequest(URL url, JSONBuilder claims, Session session, KeyPair keypair) 199 throws AcmeException { 200 return sendSignedRequest(url, claims, session, keypair, null, MIME_JSON); 201 } 202 203 @Override 204 public JSON readJsonResponse() throws AcmeException { 205 expectContentType(Set.of(MIME_JSON, MIME_JSON_PROBLEM)); 206 207 try (var in = getResponseBody()) { 208 var result = JSON.parse(in); 209 LOG.debug("Result JSON: {}", result); 210 return result; 211 } catch (IOException ex) { 212 throw new AcmeNetworkException(ex); 213 } 214 } 215 216 @Override 217 public List<X509Certificate> readCertificates() throws AcmeException { 218 expectContentType(Set.of(MIME_CERTIFICATE_CHAIN)); 219 220 try (var in = new TrimmingInputStream(getResponseBody())) { 221 var cf = CertificateFactory.getInstance("X.509"); 222 return cf.generateCertificates(in).stream() 223 .map(X509Certificate.class::cast) 224 .toList(); 225 } catch (IOException ex) { 226 throw new AcmeNetworkException(ex); 227 } catch (CertificateException ex) { 228 throw new AcmeProtocolException("Failed to read certificate", ex); 229 } 230 } 231 232 @Override 233 public Optional<String> getNonce() { 234 var nonceHeaderOpt = getResponse().headers() 235 .firstValue(REPLAY_NONCE_HEADER) 236 .map(String::trim) 237 .filter(not(String::isEmpty)); 238 if (nonceHeaderOpt.isPresent()) { 239 var nonceHeader = nonceHeaderOpt.get(); 240 241 if (!AcmeUtils.isValidBase64Url(nonceHeader)) { 242 throw new AcmeProtocolException("Invalid replay nonce: " + nonceHeader); 243 } 244 245 LOG.debug("Replay Nonce: {}", nonceHeader); 246 } 247 return nonceHeaderOpt; 248 } 249 250 @Override 251 public URL getLocation() { 252 return getResponse().headers() 253 .firstValue(LOCATION_HEADER) 254 .map(l -> { 255 LOG.debug("Location: {}", l); 256 return l; 257 }) 258 .map(this::resolveRelative) 259 .orElseThrow(() -> new AcmeProtocolException("location header is missing")); 260 } 261 262 @Override 263 public Optional<ZonedDateTime> getLastModified() { 264 return getResponse().headers() 265 .firstValue(LAST_MODIFIED_HEADER) 266 .map(lm -> { 267 try { 268 return ZonedDateTime.parse(lm, RFC_1123_DATE_TIME); 269 } catch (DateTimeParseException ex) { 270 LOG.debug("Ignored invalid Last-Modified date: {}", lm, ex); 271 return null; 272 } 273 }); 274 } 275 276 @Override 277 public Optional<ZonedDateTime> getExpiration() { 278 var cacheControlHeader = getResponse().headers() 279 .firstValue(CACHE_CONTROL_HEADER) 280 .filter(not(h -> NO_CACHE_PATTERN.matcher(h).matches())) 281 .map(MAX_AGE_PATTERN::matcher) 282 .filter(Matcher::matches) 283 .map(m -> Integer.parseInt(m.group(1))) 284 .filter(maxAge -> maxAge != 0) 285 .map(maxAge -> ZonedDateTime.now(ZoneId.of("UTC")).plusSeconds(maxAge)); 286 287 if (cacheControlHeader.isPresent()) { 288 return cacheControlHeader; 289 } 290 291 return getResponse().headers() 292 .firstValue(EXPIRES_HEADER) 293 .flatMap(header -> { 294 try { 295 return Optional.of(ZonedDateTime.parse(header, RFC_1123_DATE_TIME)); 296 } catch (DateTimeParseException ex) { 297 LOG.debug("Ignored invalid Expires date: {}", header, ex); 298 return Optional.empty(); 299 } 300 }); 301 } 302 303 @Override 304 public Collection<URL> getLinks(String relation) { 305 return collectLinks(relation).stream() 306 .map(this::resolveRelative) 307 .toList(); 308 } 309 310 @Override 311 public void close() { 312 lastResponse = null; 313 } 314 315 /** 316 * Sends a HTTP request via http client. This is the central method to be used for 317 * sending. It will create a {@link HttpRequest} by using the request builder, 318 * configure commnon headers, and then send the request via {@link HttpClient}. 319 * 320 * @param session 321 * {@link Session} to be used for sending 322 * @param url 323 * Target {@link URL} 324 * @param body 325 * Callback that completes the {@link HttpRequest.Builder} with the request 326 * body (e.g. HTTP method, request body, more headers). 327 */ 328 protected void sendRequest(Session session, URL url, Consumer<HttpRequest.Builder> body) throws IOException { 329 try { 330 var builder = httpConnector.createRequestBuilder(url) 331 .header(ACCEPT_CHARSET_HEADER, DEFAULT_CHARSET) 332 .header(ACCEPT_LANGUAGE_HEADER, session.getLanguageHeader()); 333 334 if (session.networkSettings().isCompressionEnabled()) { 335 builder.header(ACCEPT_ENCODING_HEADER, "gzip"); 336 } 337 338 body.accept(builder); 339 340 lastResponse = httpClient.send(builder.build(), HttpResponse.BodyHandlers.ofInputStream()); 341 } catch (InterruptedException ex) { 342 throw new IOException("Request was interrupted", ex); 343 } 344 } 345 346 /** 347 * Sends a signed POST request. 348 * 349 * @param url 350 * {@link URL} to send the request to. 351 * @param claims 352 * {@link JSONBuilder} containing claims. {@code null} for POST-as-GET 353 * request. 354 * @param session 355 * {@link Session} instance to be used for signing and tracking 356 * @param keypair 357 * {@link KeyPair} to be used for signing 358 * @param accountLocation 359 * If set, the account location is set as "kid" header. If {@code null}, the 360 * public key is set as "jwk" header. 361 * @param accept 362 * Accept header 363 * @return HTTP 200 class status that was returned 364 */ 365 protected int sendSignedRequest(URL url, @Nullable JSONBuilder claims, Session session, 366 KeyPair keypair, @Nullable URL accountLocation, String accept) throws AcmeException { 367 Objects.requireNonNull(url, "url"); 368 Objects.requireNonNull(session, "session"); 369 Objects.requireNonNull(keypair, "keypair"); 370 Objects.requireNonNull(accept, "accept"); 371 assertConnectionIsClosed(); 372 373 var attempt = 1; 374 while (true) { 375 try { 376 return performRequest(url, claims, session, keypair, accountLocation, accept); 377 } catch (AcmeServerException ex) { 378 if (!BAD_NONCE_ERROR.equals(ex.getType())) { 379 throw ex; 380 } 381 if (attempt == MAX_ATTEMPTS) { 382 throw ex; 383 } 384 LOG.info("Bad Replay Nonce, trying again (attempt {}/{})", attempt, MAX_ATTEMPTS); 385 attempt++; 386 } 387 } 388 } 389 390 /** 391 * Performs the POST request. 392 * 393 * @param url 394 * {@link URL} to send the request to. 395 * @param claims 396 * {@link JSONBuilder} containing claims. {@code null} for POST-as-GET 397 * request. 398 * @param session 399 * {@link Session} instance to be used for signing and tracking 400 * @param keypair 401 * {@link KeyPair} to be used for signing 402 * @param accountLocation 403 * If set, the account location is set as "kid" header. If {@code null}, the 404 * public key is set as "jwk" header. 405 * @param accept 406 * Accept header 407 * @return HTTP 200 class status that was returned 408 */ 409 private int performRequest(URL url, @Nullable JSONBuilder claims, Session session, 410 KeyPair keypair, @Nullable URL accountLocation, String accept) 411 throws AcmeException { 412 try (var nonceHolder = session.lockNonce()) { 413 if (nonceHolder.getNonce() == null) { 414 resetNonce(session); 415 } 416 417 var jose = JoseUtils.createJoseRequest( 418 url, 419 keypair, 420 claims, 421 nonceHolder.getNonce(), 422 accountLocation != null ? accountLocation.toString() : null 423 ); 424 425 var outputData = jose.toString(); 426 427 sendRequest(session, url, builder -> { 428 builder.POST(HttpRequest.BodyPublishers.ofString(outputData)); 429 builder.header(ACCEPT_HEADER, accept); 430 builder.header(CONTENT_TYPE_HEADER, "application/jose+json"); 431 }); 432 433 logHeaders(); 434 435 nonceHolder.setNonce(getNonce().orElse(null)); 436 437 var rc = getResponse().statusCode(); 438 if (rc != HTTP_OK && rc != HTTP_CREATED) { 439 throwAcmeException(); 440 } 441 return rc; 442 } catch (IOException ex) { 443 throw new AcmeNetworkException(ex); 444 } 445 } 446 447 @Override 448 public Optional<Instant> getRetryAfter() { 449 return getResponse().headers() 450 .firstValue(RETRY_AFTER_HEADER) 451 .map(this::parseRetryAfterHeader); 452 } 453 454 /** 455 * Parses the content of a Retry-After header. The header can either contain a 456 * relative or an absolute time. 457 * 458 * @param header 459 * Retry-After header 460 * @return Instant given in the header 461 * @throws AcmeProtocolException 462 * if the header content is invalid 463 */ 464 private Instant parseRetryAfterHeader(String header) { 465 // See RFC 2616 section 14.37 466 try { 467 // delta-seconds 468 if (DIGITS_ONLY_PATTERN.matcher(header).matches()) { 469 var delta = Integer.parseInt(header); 470 var date = getResponse().headers().firstValue(DATE_HEADER) 471 .map(d -> ZonedDateTime.parse(d, RFC_1123_DATE_TIME).toInstant()) 472 .orElseGet(Instant::now); 473 return date.plusSeconds(delta); 474 } 475 476 // HTTP-date 477 return ZonedDateTime.parse(header, RFC_1123_DATE_TIME).toInstant(); 478 } catch (RuntimeException ex) { 479 throw new AcmeProtocolException("Bad retry-after header value: " + header, ex); 480 } 481 } 482 483 /** 484 * Provides an {@link InputStream} of the response body. If the stream is compressed, 485 * it will also take care for decompression. 486 */ 487 private InputStream getResponseBody() throws IOException { 488 var stream = getResponse().body(); 489 if (stream == null) { 490 throw new AcmeProtocolException("Unexpected empty response"); 491 } 492 493 if (getResponse().headers().firstValue("Content-Encoding") 494 .filter("gzip"::equalsIgnoreCase) 495 .isPresent()) { 496 stream = new GZIPInputStream(stream); 497 } 498 499 return stream; 500 } 501 502 /** 503 * Throws an {@link AcmeException}. This method throws an exception that tries to 504 * explain the error as precisely as possible. 505 */ 506 private void throwAcmeException() throws AcmeException { 507 try { 508 if (getResponse().headers().firstValue(CONTENT_TYPE_HEADER) 509 .map(AcmeUtils::getContentType) 510 .filter(MIME_JSON_PROBLEM::equals) 511 .isEmpty()) { 512 // Generic HTTP error 513 throw new AcmeException("HTTP " + getResponse().statusCode()); 514 } 515 516 var problem = new Problem(readJsonResponse(), getResponse().request().uri().toURL()); 517 518 var error = AcmeUtils.stripErrorPrefix(problem.getType().toString()); 519 520 if ("unauthorized".equals(error)) { 521 throw new AcmeUnauthorizedException(problem); 522 } 523 524 if ("userActionRequired".equals(error)) { 525 var tos = collectLinks("terms-of-service").stream() 526 .findFirst() 527 .map(this::resolveUri) 528 .orElse(null); 529 throw new AcmeUserActionRequiredException(problem, tos); 530 } 531 532 if ("rateLimited".equals(error)) { 533 var retryAfter = getRetryAfter(); 534 var rateLimits = getLinks("help"); 535 throw new AcmeRateLimitedException(problem, retryAfter.orElse(null), rateLimits); 536 } 537 538 throw new AcmeServerException(problem); 539 } catch (IOException ex) { 540 throw new AcmeNetworkException(ex); 541 } 542 } 543 544 /** 545 * Checks if the returned content type is in the list of expected types. 546 * 547 * @param expectedTypes 548 * content types that are accepted 549 * @throws AcmeProtocolException 550 * if the returned content type is different 551 */ 552 private void expectContentType(Set<String> expectedTypes) { 553 var contentType = getResponse().headers() 554 .firstValue(CONTENT_TYPE_HEADER) 555 .map(AcmeUtils::getContentType) 556 .orElseThrow(() -> new AcmeProtocolException("No content type header found")); 557 if (!expectedTypes.contains(contentType)) { 558 throw new AcmeProtocolException("Unexpected content type: " + contentType); 559 } 560 } 561 562 /** 563 * Returns the response of the last request. If there is no connection currently 564 * open, an exception is thrown instead. 565 * <p> 566 * Note that the response provides an {@link InputStream} that can be read only 567 * once. 568 */ 569 private HttpResponse<InputStream> getResponse() { 570 if (lastResponse == null) { 571 throw new IllegalStateException("Not connected."); 572 } 573 return lastResponse; 574 } 575 576 /** 577 * Asserts that the connection is currently closed. Throws an exception if not. 578 */ 579 private void assertConnectionIsClosed() { 580 if (lastResponse != null) { 581 throw new IllegalStateException("Previous connection is not closed."); 582 } 583 } 584 585 /** 586 * Log all HTTP headers in debug mode. 587 */ 588 private void logHeaders() { 589 if (!LOG.isDebugEnabled()) { 590 return; 591 } 592 593 getResponse().headers().map().forEach((key, headers) -> 594 headers.forEach(value -> 595 LOG.debug("HEADER {}: {}", key, value) 596 ) 597 ); 598 } 599 600 /** 601 * Collects links of the given relation. 602 * 603 * @param relation 604 * Link relation 605 * @return Collection of links, unconverted 606 */ 607 private Collection<String> collectLinks(String relation) { 608 var p = Pattern.compile("<(.*?)>\\s*;\\s*rel=\"?" + Pattern.quote(relation) + "\"?"); 609 610 return getResponse().headers().allValues(LINK_HEADER) 611 .stream() 612 .map(p::matcher) 613 .filter(Matcher::matches) 614 .map(m -> m.group(1)) 615 .peek(location -> LOG.debug("Link: {} -> {}", relation, location)) 616 .toList(); 617 } 618 619 /** 620 * Resolves a relative link against the connection's last URL. 621 * 622 * @param link 623 * Link to resolve. Absolute links are just converted to an URL. 624 * @return Absolute URL of the given link 625 */ 626 private URL resolveRelative(String link) { 627 try { 628 return resolveUri(link).toURL(); 629 } catch (MalformedURLException ex) { 630 throw new AcmeProtocolException("Cannot resolve relative link: " + link, ex); 631 } 632 } 633 634 /** 635 * Resolves a relative URI against the connection's last URL. 636 * 637 * @param uri 638 * URI to resolve 639 * @return Absolute URI of the given link 640 */ 641 private URI resolveUri(String uri) { 642 return getResponse().request().uri().resolve(uri); 643 } 644 645}