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;
015
016import java.io.Serial;
017import java.net.URI;
018import java.net.URL;
019import java.security.KeyPair;
020import java.util.ArrayList;
021import java.util.Arrays;
022import java.util.Iterator;
023import java.util.List;
024import java.util.Objects;
025import java.util.Optional;
026
027import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
028import org.shredzone.acme4j.connector.Resource;
029import org.shredzone.acme4j.connector.ResourceIterator;
030import org.shredzone.acme4j.exception.AcmeException;
031import org.shredzone.acme4j.exception.AcmeNotSupportedException;
032import org.shredzone.acme4j.exception.AcmeProtocolException;
033import org.shredzone.acme4j.exception.AcmeServerException;
034import org.shredzone.acme4j.toolbox.AcmeUtils;
035import org.shredzone.acme4j.toolbox.JSON.Value;
036import org.shredzone.acme4j.toolbox.JSONBuilder;
037import org.shredzone.acme4j.toolbox.JoseUtils;
038import org.slf4j.Logger;
039import org.slf4j.LoggerFactory;
040
041/**
042 * A representation of an account at the ACME server.
043 */
044public class Account extends AcmeJsonResource {
045    @Serial
046    private static final long serialVersionUID = 7042863483428051319L;
047    private static final Logger LOG = LoggerFactory.getLogger(Account.class);
048
049    private static final String KEY_TOS_AGREED = "termsOfServiceAgreed";
050    private static final String KEY_ORDERS = "orders";
051    private static final String KEY_CONTACT = "contact";
052    private static final String KEY_STATUS = "status";
053    private static final String KEY_EXTERNAL_ACCOUNT_BINDING = "externalAccountBinding";
054
055    protected Account(Login login, URL location) {
056        super(login, location);
057    }
058
059    /**
060     * Returns if the user agreed to the terms of service.
061     *
062     * @return {@code true} if the user agreed to the terms of service. May be
063     *         empty if the server did not provide such an information.
064     */
065    public Optional<Boolean> getTermsOfServiceAgreed() {
066        return getJSON().get(KEY_TOS_AGREED).map(Value::asBoolean);
067    }
068
069    /**
070     * List of registered contact addresses (emails, phone numbers etc).
071     * <p>
072     * This list is unmodifiable. Use {@link #modify()} to change the contacts. May be
073     * empty, but is never {@code null}.
074     */
075    public List<URI> getContacts() {
076        return getJSON().get(KEY_CONTACT)
077                .asArray()
078                .stream()
079                .map(Value::asURI)
080                .toList();
081    }
082
083    /**
084     * Returns the current status of the account.
085     * <p>
086     * Possible values are: {@link Status#VALID}, {@link Status#DEACTIVATED},
087     * {@link Status#REVOKED}.
088     */
089    public Status getStatus() {
090        return getJSON().get(KEY_STATUS).asStatus();
091    }
092
093    /**
094     * Returns {@code true} if the account is bound to an external non-ACME account.
095     *
096     * @since 2.8
097     */
098    public boolean hasExternalAccountBinding() {
099        return getJSON().contains(KEY_EXTERNAL_ACCOUNT_BINDING);
100    }
101
102    /**
103     * Returns the key identifier of the external non-ACME account. If this account is
104     * not bound to an external account, the result is empty.
105     *
106     * @since 2.8
107     */
108    public Optional<String> getKeyIdentifier() {
109        return getJSON().get(KEY_EXTERNAL_ACCOUNT_BINDING)
110                .optional().map(Value::asObject)
111                .map(j -> j.get("protected")).map(Value::asEncodedObject)
112                .map(j -> j.get("kid")).map(Value::asString);
113    }
114
115    /**
116     * Returns an {@link Iterator} of all {@link Order} belonging to this
117     * {@link Account}.
118     * <p>
119     * Using the iterator will initiate one or more requests to the ACME server.
120     *
121     * @return {@link Iterator} instance that returns {@link Order} objects in no specific
122     * sorting order. {@link Iterator#hasNext()} and {@link Iterator#next()} may throw
123     * {@link AcmeProtocolException} if a batch of authorization URIs could not be fetched
124     * from the server.
125     */
126    public Iterator<Order> getOrders() {
127        var ordersUrl = getJSON().get(KEY_ORDERS).optional().map(Value::asURL);
128        if (ordersUrl.isEmpty()) {
129            // Let's Encrypt does not provide this field at the moment, although it's required.
130            // See https://github.com/letsencrypt/boulder/issues/3335
131            throw new AcmeNotSupportedException("getOrders()");
132        }
133        return new ResourceIterator<>(getLogin(), KEY_ORDERS, ordersUrl.get(), Login::bindOrder);
134    }
135
136    /**
137     * Creates a builder for a new {@link Order}.
138     *
139     * @return {@link OrderBuilder} object
140     */
141    public OrderBuilder newOrder() {
142        return getLogin().newOrder();
143    }
144
145    /**
146     * Pre-authorizes a domain. The CA will check if it accepts the domain for
147     * certification, and returns the necessary challenges.
148     * <p>
149     * Some servers may not allow pre-authorization.
150     * <p>
151     * It is not possible to pre-authorize wildcard domains.
152     *
153     * @param domain
154     *            Domain name to be pre-authorized. IDN names are accepted and will be ACE
155     *            encoded automatically.
156     * @return {@link Authorization} object for this domain
157     * @throws AcmeException
158     *             if the server does not allow pre-authorization
159     * @throws AcmeServerException
160     *             if the server allows pre-authorization, but will refuse to issue a
161     *             certificate for this domain
162     */
163    public Authorization preAuthorizeDomain(String domain) throws AcmeException {
164        Objects.requireNonNull(domain, "domain");
165        if (domain.isEmpty()) {
166            throw new IllegalArgumentException("domain must not be empty");
167        }
168        return preAuthorize(Identifier.dns(domain));
169    }
170
171    /**
172     * Pre-authorizes an {@link Identifier}. The CA will check if it accepts the
173     * identifier for certification, and returns the necessary challenges.
174     * <p>
175     * Some servers may not allow pre-authorization.
176     * <p>
177     * It is not possible to pre-authorize wildcard domains.
178     *
179     * @param identifier
180     *            {@link Identifier} to be pre-authorized.
181     * @return {@link Authorization} object for this identifier
182     * @throws AcmeException
183     *             if the server does not allow pre-authorization
184     * @throws AcmeServerException
185     *             if the server allows pre-authorization, but will refuse to issue a
186     *             certificate for this identifier
187     * @since 2.3
188     */
189    public Authorization preAuthorize(Identifier identifier) throws AcmeException {
190        Objects.requireNonNull(identifier, "identifier");
191
192        var newAuthzUrl = getSession().resourceUrl(Resource.NEW_AUTHZ);
193
194        if (identifier.toMap().containsKey(Identifier.KEY_SUBDOMAIN_AUTH_ALLOWED)
195                && !getSession().getMetadata().isSubdomainAuthAllowed()) {
196            throw new AcmeNotSupportedException("subdomain-auth");
197        }
198
199        LOG.debug("preAuthorize {}", identifier);
200        try (var conn = getSession().connect()) {
201            var claims = new JSONBuilder();
202            claims.put("identifier", identifier.toMap());
203
204            conn.sendSignedRequest(newAuthzUrl, claims, getLogin());
205
206            var auth = getLogin().bindAuthorization(conn.getLocation());
207            auth.setJSON(conn.readJsonResponse());
208            return auth;
209        }
210    }
211
212    /**
213     * Changes the {@link KeyPair} associated with the account.
214     * <p>
215     * After a successful call, the new key pair is already set in the associated
216     * {@link Login}. The old key pair can be discarded.
217     *
218     * @param newKeyPair
219     *         new {@link KeyPair} to be used for identifying this account
220     */
221    public void changeKey(KeyPair newKeyPair) throws AcmeException {
222        Objects.requireNonNull(newKeyPair, "newKeyPair");
223        if (Arrays.equals(getLogin().getPublicKey().getEncoded(),
224                        newKeyPair.getPublic().getEncoded())) {
225            throw new IllegalArgumentException("newKeyPair must actually be a new key pair");
226        }
227
228        LOG.debug("key-change");
229
230        try (var conn = getSession().connect()) {
231            var keyChangeUrl = getSession().resourceUrl(Resource.KEY_CHANGE);
232
233            var payloadClaim = new JSONBuilder();
234            payloadClaim.put("account", getLocation());
235            payloadClaim.putKey("oldKey", getLogin().getPublicKey());
236
237            var jose = JoseUtils.createJoseRequest(keyChangeUrl, newKeyPair,
238                    payloadClaim, null, null);
239
240            conn.sendSignedRequest(keyChangeUrl, jose, getLogin());
241
242            getLogin().setKeyPair(newKeyPair);
243        }
244    }
245
246    /**
247     * Permanently deactivates an account. Related certificates may still be valid after
248     * account deactivation, and need to be revoked separately if neccessary.
249     * <p>
250     * A deactivated account cannot be reactivated!
251     */
252    public void deactivate() throws AcmeException {
253        LOG.debug("deactivate");
254        try (var conn = getSession().connect()) {
255            var claims = new JSONBuilder();
256            claims.put(KEY_STATUS, "deactivated");
257
258            conn.sendSignedRequest(getLocation(), claims, getLogin());
259            setJSON(conn.readJsonResponse());
260        }
261    }
262
263    /**
264     * Modifies the account data of the account.
265     *
266     * @return {@link EditableAccount} where the account can be modified
267     */
268    public EditableAccount modify() {
269        return new EditableAccount();
270    }
271
272    /**
273     * Provides editable properties of an {@link Account}.
274     */
275    public class EditableAccount {
276        private final List<URI> editContacts = new ArrayList<>();
277
278        private EditableAccount() {
279            editContacts.addAll(Account.this.getContacts());
280        }
281
282        /**
283         * Returns the list of all contact URIs for modification. Use the {@link List}
284         * methods to modify the contact list.
285         * <p>
286         * The modified list is not validated. If you change entries, you have to make
287         * sure that they are valid according to the RFC. It is recommended to use
288         * the {@code addContact()} methods below to add new contacts to the list.
289         */
290        @SuppressFBWarnings("EI_EXPOSE_REP")   // behavior is intended
291        public List<URI> getContacts() {
292            return editContacts;
293        }
294
295        /**
296         * Adds a new Contact to the account.
297         *
298         * @param contact
299         *            Contact URI
300         * @return itself
301         */
302        public EditableAccount addContact(URI contact) {
303            AcmeUtils.validateContact(contact);
304            editContacts.add(contact);
305            return this;
306        }
307
308        /**
309         * Adds a new Contact to the account.
310         * <p>
311         * This is a convenience call for {@link #addContact(URI)}.
312         *
313         * @param contact
314         *            Contact URI as string
315         * @return itself
316         */
317        public EditableAccount addContact(String contact) {
318            addContact(URI.create(contact));
319            return this;
320        }
321
322        /**
323         * Adds a new Contact email to the account.
324         * <p>
325         * This is a convenience call for {@link #addContact(String)} that doesn't
326         * require to prepend the email address with the "mailto" scheme.
327         *
328         * @param email
329         *            Contact email without "mailto" scheme (e.g. test@gmail.com)
330         * @return itself
331         */
332        public EditableAccount addEmail(String email) {
333            addContact("mailto:" + email);
334            return this;
335        }
336
337        /**
338         * Commits the changes and updates the account.
339         */
340        public void commit() throws AcmeException {
341            LOG.debug("modify/commit");
342            try (var conn = getSession().connect()) {
343                var claims = new JSONBuilder();
344                if (!editContacts.isEmpty()) {
345                    claims.put(KEY_CONTACT, editContacts);
346                }
347
348                conn.sendSignedRequest(getLocation(), claims, getLogin());
349                setJSON(conn.readJsonResponse());
350            }
351        }
352    }
353
354}