001/*
002 * acme4j - Java ACME client
003 *
004 * Copyright (C) 2015 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.challenge;
015
016import java.io.Serial;
017import java.time.Duration;
018import java.time.Instant;
019import java.util.EnumSet;
020import java.util.Optional;
021
022import org.shredzone.acme4j.AcmeJsonResource;
023import org.shredzone.acme4j.Login;
024import org.shredzone.acme4j.PollableResource;
025import org.shredzone.acme4j.Problem;
026import org.shredzone.acme4j.Status;
027import org.shredzone.acme4j.exception.AcmeException;
028import org.shredzone.acme4j.exception.AcmeProtocolException;
029import org.shredzone.acme4j.toolbox.JSON;
030import org.shredzone.acme4j.toolbox.JSON.Value;
031import org.shredzone.acme4j.toolbox.JSONBuilder;
032import org.slf4j.Logger;
033import org.slf4j.LoggerFactory;
034
035/**
036 * A generic challenge. It can be used as a base class for actual challenge
037 * implementations, but it is also used if the ACME server offers a proprietary challenge
038 * that is unknown to acme4j.
039 * <p>
040 * Subclasses must override {@link Challenge#acceptable(String)} so it only accepts its
041 * own type. {@link Challenge#prepareResponse(JSONBuilder)} can be overridden to put all
042 * required data to the challenge response.
043 */
044public class Challenge extends AcmeJsonResource implements PollableResource {
045    @Serial
046    private static final long serialVersionUID = 2338794776848388099L;
047    private static final Logger LOG = LoggerFactory.getLogger(Challenge.class);
048
049    protected static final String KEY_TYPE = "type";
050    protected static final String KEY_URL = "url";
051    protected static final String KEY_STATUS = "status";
052    protected static final String KEY_VALIDATED = "validated";
053    protected static final String KEY_ERROR = "error";
054
055    /**
056     * Creates a new generic {@link Challenge} object.
057     *
058     * @param login
059     *            {@link Login} the resource is bound with
060     * @param data
061     *            {@link JSON} challenge data
062     */
063    public Challenge(Login login, JSON data) {
064        super(login, data.get(KEY_URL).asURL());
065        setJSON(data);
066    }
067
068    /**
069     * Returns the challenge type by name (e.g. "http-01").
070     */
071    public String getType() {
072        return getJSON().get(KEY_TYPE).asString();
073    }
074
075    /**
076     * Returns the current status of the challenge.
077     * <p>
078     * Possible values are: {@link Status#PENDING}, {@link Status#PROCESSING},
079     * {@link Status#VALID}, {@link Status#INVALID}.
080     * <p>
081     * A challenge is only completed when it reaches either status {@link Status#VALID} or
082     * {@link Status#INVALID}.
083     */
084    @Override
085    public Status getStatus() {
086        return getJSON().get(KEY_STATUS).asStatus();
087    }
088
089    /**
090     * Returns the validation date, if returned by the server.
091     */
092    public Optional<Instant> getValidated() {
093        return getJSON().get(KEY_VALIDATED).map(Value::asInstant);
094    }
095
096    /**
097     * Returns a reason why the challenge has failed in the past, if returned by the
098     * server. If there are multiple errors, they can be found in
099     * {@link Problem#getSubProblems()}.
100     */
101    public Optional<Problem> getError() {
102        return getJSON().get(KEY_ERROR).map(it -> it.asProblem(getLocation()));
103    }
104
105    /**
106     * Prepares the response message for triggering the challenge. Subclasses can add
107     * fields to the {@link JSONBuilder} as required by the challenge. Implementations of
108     * subclasses should make sure that {@link #prepareResponse(JSONBuilder)} of the
109     * superclass is invoked.
110     *
111     * @param response
112     *         {@link JSONBuilder} to write the response to
113     */
114    protected void prepareResponse(JSONBuilder response) {
115        // Do nothing here...
116    }
117
118    /**
119     * Checks if the type is acceptable to this challenge. This generic class only checks
120     * if the type is not blank. Subclasses should instead check if the given type matches
121     * expected challenge type.
122     *
123     * @param type
124     *         Type to check
125     * @return {@code true} if acceptable, {@code false} if not
126     */
127    protected boolean acceptable(String type) {
128        return type != null && !type.trim().isEmpty();
129    }
130
131    @Override
132    protected void setJSON(JSON json) {
133        var type = json.get(KEY_TYPE).asString();
134
135        if (!acceptable(type)) {
136            throw new AcmeProtocolException("incompatible type " + type + " for this challenge");
137        }
138
139        var loc = json.get(KEY_URL).asString();
140        if (!loc.equals(getLocation().toString())) {
141            throw new AcmeProtocolException("challenge has changed its location");
142        }
143
144        super.setJSON(json);
145    }
146
147    /**
148     * Triggers this {@link Challenge}. The ACME server is requested to validate the
149     * response. Note that the validation is performed asynchronously by the ACME server.
150     * <p>
151     * After a challenge is triggered, it changes to {@link Status#PENDING}. As soon as
152     * validation takes place, it changes to {@link Status#PROCESSING}. After validation
153     * the status changes to {@link Status#VALID} or {@link Status#INVALID}, depending on
154     * the outcome of the validation.
155     * <p>
156     * If the challenge requires a resource to be set on your side (e.g. a DNS record or
157     * an HTTP file), it <em>must</em> be reachable from public before {@link #trigger()}
158     * is invoked, and <em>must not</em> be taken down until the challenge has reached
159     * {@link Status#VALID} or {@link Status#INVALID}.
160     * <p>
161     * If this method is invoked a second time, the ACME server is requested to retry the
162     * validation. This can be useful if the client state has changed, for example after a
163     * firewall rule has been updated.
164     *
165     * @see #waitForCompletion(Duration)
166     */
167    public void trigger() throws AcmeException {
168        LOG.debug("trigger");
169        try (var conn = getSession().connect()) {
170            var claims = new JSONBuilder();
171            prepareResponse(claims);
172
173            conn.sendSignedRequest(getLocation(), claims, getLogin());
174            setJSON(conn.readJsonResponse());
175        }
176    }
177
178    /**
179     * Waits until the challenge is completed.
180     * <p>
181     * Is is completed if it reaches either {@link Status#VALID} or
182     * {@link Status#INVALID}.
183     * <p>
184     * This method is synchronous and blocks the current thread.
185     *
186     * @param timeout
187     *         Timeout until a terminal status must have been reached
188     * @return Status that was reached
189     * @since 3.4.0
190     */
191    public Status waitForCompletion(Duration timeout)
192            throws AcmeException, InterruptedException {
193        return waitForStatus(EnumSet.of(Status.VALID, Status.INVALID), timeout);
194    }
195
196}