source: josm/trunk/src/org/openstreetmap/josm/io/OsmConnection.java @ 12992

Last change on this file since 12992 was 12992, checked in by Don-vip, 14 months ago

fix #15435 - do not cache incorrect login credentials when using basic auth

  • Property svn:eol-style set to native
File size: 7.9 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.io;
3
4import static org.openstreetmap.josm.tools.I18n.tr;
5
6import java.lang.reflect.InvocationTargetException;
7import java.net.Authenticator.RequestorType;
8import java.net.MalformedURLException;
9import java.net.URL;
10import java.nio.charset.StandardCharsets;
11import java.util.Base64;
12import java.util.Objects;
13
14import org.openstreetmap.josm.data.oauth.OAuthAccessTokenHolder;
15import org.openstreetmap.josm.data.oauth.OAuthParameters;
16import org.openstreetmap.josm.io.auth.CredentialsAgentException;
17import org.openstreetmap.josm.io.auth.CredentialsAgentResponse;
18import org.openstreetmap.josm.io.auth.CredentialsManager;
19import org.openstreetmap.josm.tools.HttpClient;
20import org.openstreetmap.josm.tools.JosmRuntimeException;
21import org.openstreetmap.josm.tools.Logging;
22
23import oauth.signpost.OAuthConsumer;
24import oauth.signpost.exception.OAuthException;
25
26/**
27 * Base class that handles common things like authentication for the reader and writer
28 * to the osm server.
29 *
30 * @author imi
31 */
32public class OsmConnection {
33
34    private static final String BASIC_AUTH = "Basic ";
35
36    protected boolean cancel;
37    protected HttpClient activeConnection;
38    protected OAuthParameters oauthParameters;
39
40    /**
41     * Retrieves OAuth access token.
42     * @since 12803
43     */
44    public interface OAuthAccessTokenFetcher {
45        /**
46         * Obtains an OAuth access token for the connection. Afterwards, the token is accessible via {@link OAuthAccessTokenHolder}.
47         * @param serverUrl the URL to OSM server
48         * @throws InterruptedException if we're interrupted while waiting for the event dispatching thread to finish OAuth authorization task
49         * @throws InvocationTargetException if an exception is thrown while running OAuth authorization task
50         */
51        void obtainAccessToken(URL serverUrl) throws InvocationTargetException, InterruptedException;
52    }
53
54    static volatile OAuthAccessTokenFetcher fetcher = u -> {
55        throw new JosmRuntimeException("OsmConnection.setOAuthAccessTokenFetcher() has not been called");
56    };
57
58    /**
59     * Sets the OAuth access token fetcher.
60     * @param tokenFetcher new OAuth access token fetcher. Cannot be null
61     * @since 12803
62     */
63    public static void setOAuthAccessTokenFetcher(OAuthAccessTokenFetcher tokenFetcher) {
64        fetcher = Objects.requireNonNull(tokenFetcher, "tokenFetcher");
65    }
66
67    /**
68     * Cancels the connection.
69     */
70    public void cancel() {
71        cancel = true;
72        synchronized (this) {
73            if (activeConnection != null) {
74                activeConnection.disconnect();
75            }
76        }
77    }
78
79    /**
80     * Retrieves login from basic authentication header, if set.
81     *
82     * @param con the connection
83     * @return login from basic authentication header, or {@code null}
84     * @throws OsmTransferException if something went wrong. Check for nested exceptions
85     * @since 12992
86     */
87    protected String retrieveBasicAuthorizationLogin(HttpClient con) throws OsmTransferException {
88        String auth = con.getRequestHeader("Authorization");
89        if (auth != null && auth.startsWith(BASIC_AUTH)) {
90            try {
91                String[] token = new String(Base64.getDecoder().decode(auth.substring(BASIC_AUTH.length())),
92                        StandardCharsets.UTF_8).split(":");
93                if (token.length == 2) {
94                    return token[0];
95                }
96            } catch (IllegalArgumentException e) {
97                Logging.error(e);
98            }
99        }
100        return null;
101    }
102
103    /**
104     * Adds an authentication header for basic authentication
105     *
106     * @param con the connection
107     * @throws OsmTransferException if something went wrong. Check for nested exceptions
108     */
109    protected void addBasicAuthorizationHeader(HttpClient con) throws OsmTransferException {
110        CredentialsAgentResponse response;
111        try {
112            synchronized (CredentialsManager.getInstance()) {
113                response = CredentialsManager.getInstance().getCredentials(RequestorType.SERVER,
114                con.getURL().getHost(), false /* don't know yet whether the credentials will succeed */);
115            }
116        } catch (CredentialsAgentException e) {
117            throw new OsmTransferException(e);
118        }
119        if (response != null) {
120            if (response.isCanceled()) {
121                cancel = true;
122                return;
123            } else {
124                String username = response.getUsername() == null ? "" : response.getUsername();
125                String password = response.getPassword() == null ? "" : String.valueOf(response.getPassword());
126                String token = username + ':' + password;
127                con.setHeader("Authorization", BASIC_AUTH + Base64.getEncoder().encodeToString(token.getBytes(StandardCharsets.UTF_8)));
128            }
129        }
130    }
131
132    /**
133     * Signs the connection with an OAuth authentication header
134     *
135     * @param connection the connection
136     *
137     * @throws MissingOAuthAccessTokenException if there is currently no OAuth Access Token configured
138     * @throws OsmTransferException if signing fails
139     */
140    protected void addOAuthAuthorizationHeader(HttpClient connection) throws OsmTransferException {
141        if (oauthParameters == null) {
142            oauthParameters = OAuthParameters.createFromApiUrl(OsmApi.getOsmApi().getServerUrl());
143        }
144        OAuthConsumer consumer = oauthParameters.buildConsumer();
145        OAuthAccessTokenHolder holder = OAuthAccessTokenHolder.getInstance();
146        if (!holder.containsAccessToken()) {
147            obtainAccessToken(connection);
148        }
149        if (!holder.containsAccessToken()) { // check if wizard completed
150            throw new MissingOAuthAccessTokenException();
151        }
152        consumer.setTokenWithSecret(holder.getAccessTokenKey(), holder.getAccessTokenSecret());
153        try {
154            consumer.sign(connection);
155        } catch (OAuthException e) {
156            throw new OsmTransferException(tr("Failed to sign a HTTP connection with an OAuth Authentication header"), e);
157        }
158    }
159
160    /**
161     * Obtains an OAuth access token for the connection.
162     * Afterwards, the token is accessible via {@link OAuthAccessTokenHolder} / {@link CredentialsManager}.
163     * @param connection connection for which the access token should be obtained
164     * @throws MissingOAuthAccessTokenException if the process cannot be completed successfully
165     */
166    protected void obtainAccessToken(final HttpClient connection) throws MissingOAuthAccessTokenException {
167        try {
168            final URL apiUrl = new URL(OsmApi.getOsmApi().getServerUrl());
169            if (!Objects.equals(apiUrl.getHost(), connection.getURL().getHost())) {
170                throw new MissingOAuthAccessTokenException();
171            }
172            fetcher.obtainAccessToken(apiUrl);
173            OAuthAccessTokenHolder.getInstance().setSaveToPreferences(true);
174            OAuthAccessTokenHolder.getInstance().save(CredentialsManager.getInstance());
175        } catch (MalformedURLException | InterruptedException | InvocationTargetException e) {
176            throw new MissingOAuthAccessTokenException(e);
177        }
178    }
179
180    protected void addAuth(HttpClient connection) throws OsmTransferException {
181        final String authMethod = OsmApi.getAuthMethod();
182        if ("basic".equals(authMethod)) {
183            addBasicAuthorizationHeader(connection);
184        } else if ("oauth".equals(authMethod)) {
185            addOAuthAuthorizationHeader(connection);
186        } else {
187            String msg = tr("Unexpected value for preference ''{0}''. Got ''{1}''.", "osm-server.auth-method", authMethod);
188            Logging.warn(msg);
189            throw new OsmTransferException(msg);
190        }
191    }
192
193    /**
194     * Replies true if this connection is canceled
195     *
196     * @return true if this connection is canceled
197     */
198    public boolean isCanceled() {
199        return cancel;
200    }
201}
Note: See TracBrowser for help on using the repository browser.