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;
015
016import java.net.URL;
017import java.time.Instant;
018import java.time.temporal.TemporalAmount;
019import java.util.Optional;
020import java.util.concurrent.ThreadLocalRandom;
021
022import edu.umd.cs.findbugs.annotations.Nullable;
023import org.shredzone.acme4j.connector.Connection;
024import org.shredzone.acme4j.exception.AcmeException;
025import org.shredzone.acme4j.exception.AcmeProtocolException;
026import org.shredzone.acme4j.toolbox.JSON.Value;
027import org.slf4j.Logger;
028import org.slf4j.LoggerFactory;
029
030/**
031 * Renewal Information of a certificate.
032 *
033 * @since 3.0.0
034 */
035public class RenewalInfo extends AcmeJsonResource {
036    private static final Logger LOG = LoggerFactory.getLogger(RenewalInfo.class);
037
038    protected RenewalInfo(Login login, URL location) {
039        super(login, location);
040    }
041
042    /**
043     * Returns the starting {@link Instant} of the time window the CA recommends for
044     * certificate renewal.
045     */
046    public Instant getSuggestedWindowStart() {
047        return getJSON().get("suggestedWindow").asObject().get("start").asInstant();
048    }
049
050    /**
051     * Returns the ending {@link Instant} of the time window the CA recommends for
052     * certificate renewal.
053     */
054    public Instant getSuggestedWindowEnd() {
055        return getJSON().get("suggestedWindow").asObject().get("end").asInstant();
056    }
057
058    /**
059     * An optional {@link URL} pointing to a page which may explain why the suggested
060     * renewal window is what it is.
061     */
062    public Optional<URL> getExplanation() {
063        return getJSON().get("explanationURL").optional().map(Value::asURL);
064    }
065
066    /**
067     * Checks if the given {@link Instant} is before the suggested time window, so a
068     * certificate renewal is not required yet.
069     *
070     * @param instant
071     *         {@link Instant} to check
072     * @return {@code true} if the {@link Instant} is before the time window, {@code
073     * false} otherwise.
074     */
075    public boolean renewalIsNotRequired(Instant instant) {
076        assertValidTimeWindow();
077        return instant.isBefore(getSuggestedWindowStart());
078    }
079
080    /**
081     * Checks if the given {@link Instant} is within the suggested time window, and a
082     * certificate renewal is recommended.
083     * <p>
084     * An {@link Instant} is deemed to be within the time window if it is equal to, or
085     * after {@link #getSuggestedWindowStart()}, and before {@link
086     * #getSuggestedWindowEnd()}.
087     *
088     * @param instant
089     *         {@link Instant} to check
090     * @return {@code true} if the {@link Instant} is within the time window, {@code
091     * false} otherwise.
092     */
093    public boolean renewalIsRecommended(Instant instant) {
094        assertValidTimeWindow();
095        return !instant.isBefore(getSuggestedWindowStart())
096                && instant.isBefore(getSuggestedWindowEnd());
097    }
098
099    /**
100     * Checks if the given {@link Instant} is past the time window, and a certificate
101     * renewal is overdue.
102     * <p>
103     * An {@link Instant} is deemed to be past the time window if it is equal to, or after
104     * {@link #getSuggestedWindowEnd()}.
105     *
106     * @param instant
107     *         {@link Instant} to check
108     * @return {@code true} if the {@link Instant} is past the time window, {@code false}
109     * otherwise.
110     */
111    public boolean renewalIsOverdue(Instant instant) {
112        assertValidTimeWindow();
113        return !instant.isBefore(getSuggestedWindowEnd());
114    }
115
116    /**
117     * Returns a proposed {@link Instant} when the certificate related to this
118     * {@link RenewalInfo} should be renewed.
119     * <p>
120     * This method is useful for setting alarms for renewal cron jobs. As a parameter, the
121     * frequency of the cron job is set. The resulting {@link Instant} is guaranteed to be
122     * executed in time, considering the cron job intervals.
123     * <p>
124     * This method uses {@link ThreadLocalRandom} for random numbers. It is sufficient for
125     * most cases, as only an "earliest" {@link Instant} is returned, but the actual
126     * renewal process also depends on cron job execution times and other factors like
127     * system load.
128     * <p>
129     * The result is empty if it is impossible to renew the certificate in time, under the
130     * given circumstances. This is either because the time window already ended in the
131     * past, or because the cron job would not be executed before the ending of the time
132     * window. In this case, it is recommended to renew the certificate immediately.
133     *
134     * @param frequency
135     *         Frequency of the cron job executing the certificate renewals. May be
136     *         {@code null} if there is no cron job, and the renewal is going to be
137     *         executed exactly at the given {@link Instant}.
138     * @return Random {@link Instant} when the certificate should be renewed. This instant
139     * might be slightly in the past. In this case, start the renewal process at the next
140     * possible regular moment.
141     */
142    public Optional<Instant> getRandomProposal(@Nullable TemporalAmount frequency) {
143        assertValidTimeWindow();
144        Instant start = Instant.now();
145        Instant suggestedStart = getSuggestedWindowStart();
146        if (start.isBefore(suggestedStart)) {
147            start = suggestedStart;
148        }
149
150        Instant end = getSuggestedWindowEnd();
151        if (frequency != null) {
152            end = end.minus(frequency);
153        }
154
155        if (!end.isAfter(start)) {
156            return Optional.empty();
157        }
158
159        return Optional.of(Instant.ofEpochMilli(ThreadLocalRandom.current().nextLong(
160                start.toEpochMilli(),
161                end.toEpochMilli())));
162    }
163
164    /**
165     * Asserts that the end of the suggested time window is after the start.
166     */
167    private void assertValidTimeWindow() {
168        if (getSuggestedWindowStart().isAfter(getSuggestedWindowEnd())) {
169            throw new AcmeProtocolException("Received an invalid suggested window");
170        }
171    }
172
173    @Override
174    public Optional<Instant> fetch() throws AcmeException {
175        LOG.debug("update RenewalInfo");
176        try (Connection conn = getSession().connect()) {
177            conn.sendRequest(getLocation(), getSession(), null);
178            setJSON(conn.readJsonResponse());
179            var retryAfterOpt = conn.getRetryAfter();
180            retryAfterOpt.ifPresent(instant -> LOG.debug("Retry-After: {}", instant));
181            setRetryAfter(retryAfterOpt.orElse(null));
182            return retryAfterOpt;
183        }
184    }
185
186}