001/*
002 * acme4j - Java ACME client
003 *
004 * Copyright (C) 2018 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 static java.util.Objects.requireNonNull;
017import static org.shredzone.acme4j.toolbox.AcmeUtils.getRenewalUniqueIdentifier;
018
019import java.net.MalformedURLException;
020import java.net.URI;
021import java.net.URL;
022import java.security.KeyPair;
023import java.security.cert.X509Certificate;
024import java.util.Objects;
025
026import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
027import org.shredzone.acme4j.challenge.Challenge;
028import org.shredzone.acme4j.connector.Resource;
029import org.shredzone.acme4j.exception.AcmeException;
030import org.shredzone.acme4j.exception.AcmeLazyLoadingException;
031import org.shredzone.acme4j.exception.AcmeProtocolException;
032import org.shredzone.acme4j.toolbox.JSON;
033
034/**
035 * A {@link Login} into an account.
036 * <p>
037 * A login is bound to a {@link Session}. However, a {@link Session} can handle multiple
038 * logins in parallel.
039 * <p>
040 * To create a login, you need to specify the location URI of the {@link Account}, and
041 * need to provide the {@link KeyPair} the account was created with. If the account's
042 * location URL is unknown, the account can be re-registered with the
043 * {@link AccountBuilder}, using {@link AccountBuilder#onlyExisting()} to make sure that
044 * no new account will be created. If the key pair was lost though, there is no automatic
045 * way to regain access to your account, and you have to contact your CA's support hotline
046 * for assistance.
047 * <p>
048 * Note that {@link Login} objects are intentionally not serializable, as they contain a
049 * keypair and volatile data. On distributed systems, you can create a {@link Login} to
050 * the same account for every service instance.
051 */
052public class Login {
053
054    private final Session session;
055    private final URL accountLocation;
056    private final Account account;
057    private KeyPair keyPair;
058
059    /**
060     * Creates a new {@link Login}.
061     *
062     * @param accountLocation
063     *            Account location {@link URL}
064     * @param keyPair
065     *            {@link KeyPair} of the account
066     * @param session
067     *            {@link Session} to be used
068     */
069    public Login(URL accountLocation, KeyPair keyPair, Session session) {
070        this.accountLocation = Objects.requireNonNull(accountLocation, "accountLocation");
071        this.keyPair = Objects.requireNonNull(keyPair, "keyPair");
072        this.session = Objects.requireNonNull(session, "session");
073        this.account = new Account(this);
074    }
075
076    /**
077     * Gets the {@link Session} that is used.
078     */
079    @SuppressFBWarnings("EI_EXPOSE_REP")    // behavior is intended
080    public Session getSession() {
081        return session;
082    }
083
084    /**
085     * Gets the {@link KeyPair} of the ACME account.
086     */
087    public KeyPair getKeyPair() {
088        return keyPair;
089    }
090
091    /**
092     * Gets the location {@link URL} of the account.
093     */
094    public URL getAccountLocation() {
095        return accountLocation;
096    }
097
098    /**
099     * Gets the {@link Account} that is bound to this login.
100     *
101     * @return {@link Account} bound to the login
102     */
103    @SuppressFBWarnings("EI_EXPOSE_REP")    // behavior is intended
104    public Account getAccount() {
105        return account;
106    }
107
108    /**
109     * Creates a new instance of an existing {@link Authorization} and binds it to this
110     * login.
111     *
112     * @param location
113     *         Location of the Authorization
114     * @return {@link Authorization} bound to the login
115     */
116    public Authorization bindAuthorization(URL location) {
117        return new Authorization(this, requireNonNull(location, "location"));
118    }
119
120    /**
121     * Creates a new instance of an existing {@link Certificate} and binds it to this
122     * login.
123     *
124     * @param location
125     *         Location of the Certificate
126     * @return {@link Certificate} bound to the login
127     */
128    public Certificate bindCertificate(URL location) {
129        return new Certificate(this, requireNonNull(location, "location"));
130    }
131
132    /**
133     * Creates a new instance of an existing {@link Order} and binds it to this login.
134     *
135     * @param location
136     *         Location URL of the order
137     * @return {@link Order} bound to the login
138     */
139    public Order bindOrder(URL location) {
140        return new Order(this, requireNonNull(location, "location"));
141    }
142
143    /**
144     * Creates a new instance of an existing {@link RenewalInfo} and binds it to this
145     * login.
146     *
147     * @param location
148     *         Location URL of the renewal info
149     * @return {@link RenewalInfo} bound to the login
150     * @since 3.0.0
151     */
152    public RenewalInfo bindRenewalInfo(URL location) {
153        return new RenewalInfo(this, requireNonNull(location, "location"));
154    }
155
156    /**
157     * Creates a new instance of an existing {@link RenewalInfo} and binds it to this
158     * login.
159     *
160     * @param certificate
161     *         {@link X509Certificate} to get the {@link RenewalInfo} for
162     * @return {@link RenewalInfo} bound to the login
163     * @since 3.2.0
164     */
165    public RenewalInfo bindRenewalInfo(X509Certificate certificate) throws AcmeException {
166        try {
167            var url = getSession().resourceUrl(Resource.RENEWAL_INFO).toExternalForm();
168            if (!url.endsWith("/")) {
169                url += '/';
170            }
171            url += getRenewalUniqueIdentifier(certificate);
172            return bindRenewalInfo(URI.create(url).toURL());
173        } catch (MalformedURLException ex) {
174            throw new AcmeProtocolException("Invalid RenewalInfo URL", ex);
175        }
176    }
177
178    /**
179     * Creates a new instance of an existing {@link Challenge} and binds it to this
180     * login. Use this method only if the resulting challenge type is unknown.
181     *
182     * @param location
183     *         Location URL of the challenge
184     * @return {@link Challenge} bound to the login
185     * @since 2.8
186     * @see #bindChallenge(URL, Class)
187     */
188    public Challenge bindChallenge(URL location) {
189        try (var connect = session.connect()) {
190            connect.sendSignedPostAsGetRequest(location, this);
191            return createChallenge(connect.readJsonResponse());
192        } catch (AcmeException ex) {
193            throw new AcmeLazyLoadingException(Challenge.class, location, ex);
194        }
195    }
196
197    /**
198     * Creates a new instance of an existing {@link Challenge} and binds it to this
199     * login. Use this method if the resulting challenge type is known.
200     *
201     * @param location
202     *         Location URL of the challenge
203     * @param type
204     *         Expected challenge type
205     * @return Challenge bound to the login
206     * @throws AcmeProtocolException
207     *         if the challenge found at the location does not match the expected
208     *         challenge type.
209     * @since 2.12
210     */
211    public <C extends Challenge> C bindChallenge(URL location, Class<C> type) {
212        var challenge = bindChallenge(location);
213        if (!type.isInstance(challenge)) {
214            throw new AcmeProtocolException("Challenge type " + challenge.getType()
215                    + " does not match requested class " + type);
216        }
217        return type.cast(challenge);
218    }
219
220    /**
221     * Creates a {@link Challenge} instance for the given challenge data.
222     *
223     * @param data
224     *            Challenge JSON data
225     * @return {@link Challenge} instance
226     */
227    public Challenge createChallenge(JSON data) {
228        var challenge = session.provider().createChallenge(this, data);
229        if (challenge == null) {
230            throw new AcmeProtocolException("Could not create challenge for: " + data);
231        }
232        return challenge;
233    }
234
235    /**
236     * Creates a builder for a new {@link Order}.
237     *
238     * @return {@link OrderBuilder} object
239     * @since 3.0.0
240     */
241    public OrderBuilder newOrder() {
242        return new OrderBuilder(this);
243    }
244
245    /**
246     * Sets a different {@link KeyPair}. The new key pair is only used locally in this
247     * instance, but is not set on server side!
248     */
249    protected void setKeyPair(KeyPair keyPair) {
250        this.keyPair = Objects.requireNonNull(keyPair, "keyPair");
251    }
252
253}