001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.io;
003
004import static org.openstreetmap.josm.tools.I18n.tr;
005
006import java.lang.reflect.InvocationTargetException;
007import java.net.Authenticator.RequestorType;
008import java.net.URL;
009import java.nio.charset.StandardCharsets;
010import java.util.Base64;
011import java.util.Objects;
012import java.util.Optional;
013import java.util.concurrent.CountDownLatch;
014import java.util.concurrent.TimeUnit;
015import java.util.function.Consumer;
016
017import javax.swing.JOptionPane;
018
019import org.openstreetmap.josm.data.oauth.IOAuthParameters;
020import org.openstreetmap.josm.data.oauth.IOAuthToken;
021import org.openstreetmap.josm.data.oauth.OAuth20Authorization;
022import org.openstreetmap.josm.data.oauth.OAuthAccessTokenHolder;
023import org.openstreetmap.josm.data.oauth.OAuthParameters;
024import org.openstreetmap.josm.data.oauth.OAuthVersion;
025import org.openstreetmap.josm.data.oauth.osm.OsmScopes;
026import org.openstreetmap.josm.gui.ConditionalOptionPaneUtil;
027import org.openstreetmap.josm.gui.MainApplication;
028import org.openstreetmap.josm.gui.util.GuiHelper;
029import org.openstreetmap.josm.io.auth.CredentialsAgentException;
030import org.openstreetmap.josm.io.auth.CredentialsAgentResponse;
031import org.openstreetmap.josm.io.auth.CredentialsManager;
032import org.openstreetmap.josm.io.remotecontrol.RemoteControl;
033import org.openstreetmap.josm.tools.HttpClient;
034import org.openstreetmap.josm.tools.JosmRuntimeException;
035import org.openstreetmap.josm.tools.Logging;
036import org.openstreetmap.josm.tools.Utils;
037
038/**
039 * Base class that handles common things like authentication for the reader and writer
040 * to the osm server.
041 *
042 * @author imi
043 */
044public class OsmConnection {
045
046    private static final String BASIC_AUTH = "Basic ";
047
048    protected boolean cancel;
049    protected HttpClient activeConnection;
050    protected IOAuthParameters oAuth20Parameters;
051
052    /**
053     * Retrieves OAuth access token.
054     * @since 12803
055     */
056    @FunctionalInterface
057    public interface OAuthAccessTokenFetcher {
058        /**
059         * Obtains an OAuth access token for the connection. Afterwards, the token is accessible via {@link OAuthAccessTokenHolder}.
060         * @param serverUrl the URL to OSM server
061         * @throws InterruptedException if we're interrupted while waiting for the event dispatching thread to finish OAuth authorization task
062         * @throws InvocationTargetException if an exception is thrown while running OAuth authorization task
063         */
064        void obtainAccessToken(URL serverUrl) throws InvocationTargetException, InterruptedException;
065    }
066
067    static volatile OAuthAccessTokenFetcher fetcher = u -> {
068        throw new JosmRuntimeException("OsmConnection.setOAuthAccessTokenFetcher() has not been called");
069    };
070
071    /**
072     * Sets the OAuth access token fetcher.
073     * @param tokenFetcher new OAuth access token fetcher. Cannot be null
074     * @since 12803
075     */
076    public static void setOAuthAccessTokenFetcher(OAuthAccessTokenFetcher tokenFetcher) {
077        fetcher = Objects.requireNonNull(tokenFetcher, "tokenFetcher");
078    }
079
080    /**
081     * Cancels the connection.
082     */
083    public void cancel() {
084        cancel = true;
085        synchronized (this) {
086            if (activeConnection != null) {
087                activeConnection.disconnect();
088            }
089        }
090    }
091
092    /**
093     * Retrieves login from basic authentication header, if set.
094     *
095     * @param con the connection
096     * @return login from basic authentication header, or {@code null}
097     * @throws OsmTransferException if something went wrong. Check for nested exceptions
098     * @since 12992
099     */
100    protected String retrieveBasicAuthorizationLogin(HttpClient con) throws OsmTransferException {
101        String auth = con.getRequestHeader("Authorization");
102        if (auth != null && auth.startsWith(BASIC_AUTH)) {
103            try {
104                String[] token = new String(Base64.getDecoder().decode(auth.substring(BASIC_AUTH.length())),
105                        StandardCharsets.UTF_8).split(":", -1);
106                if (token.length == 2) {
107                    return token[0];
108                }
109            } catch (IllegalArgumentException e) {
110                Logging.error(e);
111            }
112        }
113        return null;
114    }
115
116    /**
117     * Adds an authentication header for basic authentication
118     *
119     * @param con the connection
120     * @throws OsmTransferException if something went wrong. Check for nested exceptions
121     */
122    protected void addBasicAuthorizationHeader(HttpClient con) throws OsmTransferException {
123        CredentialsAgentResponse response;
124        try {
125            synchronized (CredentialsManager.getInstance()) {
126                response = CredentialsManager.getInstance().getCredentials(RequestorType.SERVER,
127                con.getURL().getHost(), false /* don't know yet whether the credentials will succeed */);
128            }
129        } catch (CredentialsAgentException e) {
130            throw new OsmTransferException(e);
131        }
132        if (response != null) {
133            if (response.isCanceled()) {
134                cancel = true;
135            } else {
136                String username = response.getUsername() == null ? "" : response.getUsername();
137                String password = response.getPassword() == null ? "" : String.valueOf(response.getPassword());
138                String token = username + ':' + password;
139                con.setHeader("Authorization", BASIC_AUTH + Base64.getEncoder().encodeToString(token.getBytes(StandardCharsets.UTF_8)));
140            }
141        }
142    }
143
144    /**
145     * Obtains an OAuth access token for the connection.
146     * Afterwards, the token is accessible via {@link OAuthAccessTokenHolder} / {@link CredentialsManager}.
147     * @throws MissingOAuthAccessTokenException if the process cannot be completed successfully
148     */
149    private void obtainOAuth20Token() throws MissingOAuthAccessTokenException {
150        if (Utils.isEmpty(this.oAuth20Parameters.getClientId())) {
151            // Without a client id the authorization request is rejected by the server with "Missing required
152            // parameter: client_id", so do not send the user to the browser at all. The message of the exception
153            // is for the log only; what the user is shown already points at the preferences, which is where the
154            // client id of an OAuth application registered on this server has to be entered.
155            throw new MissingOAuthAccessTokenException(
156                    "No OAuth client id for " + OsmApi.getOsmApi().getServerUrl() + ", cannot request a token");
157        }
158        if (!Boolean.TRUE.equals(GuiHelper.runInEDTAndWaitAndReturn(() ->
159                ConditionalOptionPaneUtil.showConfirmationDialog("oauth.oauth20.obtain.automatically",
160                    MainApplication.getMainFrame(),
161                    tr("Obtain OAuth 2.0 token for authentication?"),
162                    tr("Obtain authentication to OSM servers"),
163                    JOptionPane.YES_NO_CANCEL_OPTION,
164                    JOptionPane.QUESTION_MESSAGE, JOptionPane.YES_OPTION)))) {
165            return; // User doesn't want to perform auth
166        }
167        final boolean remoteControlIsRunning = Boolean.TRUE.equals(RemoteControl.PROP_REMOTECONTROL_ENABLED.get());
168        if (!remoteControlIsRunning) {
169            RemoteControl.start();
170        }
171        CountDownLatch done = new CountDownLatch(1);
172        Consumer<Optional<IOAuthToken>> consumer = authToken -> {
173                    if (!remoteControlIsRunning) {
174                        RemoteControl.stop();
175                    }
176                    // Clean up old token/password
177                    OAuthAccessTokenHolder.getInstance().setAccessToken(OsmApi.getOsmApi().getServerUrl(), authToken.orElse(null));
178                    OAuthAccessTokenHolder.getInstance().save(CredentialsManager.getInstance());
179                    done.countDown();
180                };
181        new OAuth20Authorization().authorize(oAuth20Parameters,
182                consumer, OsmScopes.read_gpx, OsmScopes.write_gpx,
183                OsmScopes.read_prefs, OsmScopes.write_prefs,
184                OsmScopes.write_api, OsmScopes.write_notes);
185        // Only wait at most 5 minutes
186        int counter = 0;
187        while (done.getCount() >= 0 && counter < 5) {
188            try {
189                if (done.await(1, TimeUnit.MINUTES)) {
190                    break;
191                }
192            } catch (InterruptedException e) {
193                Thread.currentThread().interrupt();
194                Logging.trace(e);
195                consumer.accept(null);
196                throw new MissingOAuthAccessTokenException(e);
197            }
198            counter++;
199        }
200    }
201
202    /**
203     * Signs the connection with an OAuth authentication header
204     *
205     * @param connection the connection
206     *
207     * @throws MissingOAuthAccessTokenException if there is currently no OAuth Access Token configured
208     * @throws OsmTransferException if signing fails
209     */
210    protected void addOAuth20AuthorizationHeader(HttpClient connection) throws OsmTransferException {
211        if (this.oAuth20Parameters == null) {
212            // The parameters are stored under the API URL, so look them up with the API URL and not with the
213            // host of the request: OAuthParameters.createFromApiUrl() reduces it to the host itself where that
214            // is what it needs.
215            this.oAuth20Parameters = OAuthParameters.createFromApiUrl(OsmApi.getOsmApi().getServerUrl(), OAuthVersion.OAuth20);
216        }
217        OAuthAccessTokenHolder holder = OAuthAccessTokenHolder.getInstance();
218        IOAuthToken token = holder.getAccessToken(connection.getURL().toExternalForm(), OAuthVersion.OAuth20);
219        if (token == null) {
220            obtainOAuth20Token();
221            token = holder.getAccessToken(connection.getURL().toExternalForm(), OAuthVersion.OAuth20);
222        }
223        if (token == null) { // check if wizard completed
224            throw new MissingOAuthAccessTokenException();
225        }
226        try {
227            token.sign(connection);
228        } catch (org.openstreetmap.josm.data.oauth.OAuthException e) {
229            throw new OsmTransferException(tr("Failed to sign a HTTP connection with an OAuth Authentication header"), e);
230        }
231    }
232
233    protected void addAuth(HttpClient connection) throws OsmTransferException {
234        final String authMethod = OsmApi.getAuthMethod();
235        switch (authMethod) {
236            case "basic":
237                addBasicAuthorizationHeader(connection);
238                return;
239            case "oauth20":
240                addOAuth20AuthorizationHeader(connection);
241                return;
242            default:
243                String msg = tr("Unexpected value for preference ''{0}''. Got ''{1}''.", "osm-server.auth-method", authMethod);
244                Logging.warn(msg);
245                throw new OsmTransferException(msg);
246        }
247    }
248
249    /**
250     * Replies true if this connection is canceled
251     *
252     * @return true if this connection is canceled
253     */
254    public boolean isCanceled() {
255        return cancel;
256    }
257}