001// License: GPL. For details, see LICENSE file. 002package org.openstreetmap.josm.data.oauth; 003 004import java.io.BufferedReader; 005import java.io.IOException; 006import java.net.URI; 007import java.net.URISyntaxException; 008import java.net.URL; 009import java.util.HashMap; 010import java.util.Map; 011 012import jakarta.json.stream.JsonParsingException; 013import org.openstreetmap.josm.io.NetworkManager; 014import org.openstreetmap.josm.io.OsmApi; 015import org.openstreetmap.josm.io.auth.CredentialsAgentException; 016import org.openstreetmap.josm.io.auth.CredentialsManager; 017import org.openstreetmap.josm.spi.preferences.Config; 018import org.openstreetmap.josm.spi.preferences.IUrls; 019import org.openstreetmap.josm.tools.HttpClient; 020import org.openstreetmap.josm.tools.JosmRuntimeException; 021import org.openstreetmap.josm.tools.Logging; 022import org.openstreetmap.josm.tools.Utils; 023 024import jakarta.json.Json; 025import jakarta.json.JsonObject; 026import jakarta.json.JsonReader; 027import jakarta.json.JsonStructure; 028import jakarta.json.JsonValue; 029 030/** 031 * This class manages an immutable set of OAuth parameters. 032 * @since 2747 (static factory class since 18991) 033 */ 034public final class OAuthParameters { 035 private static final Map<String, JsonObject> RFC8414_RESPONSES = new HashMap<>(1); 036 private static final String OSM_API_DEFAULT = "https://api.openstreetmap.org/api"; 037 private static final String OSM_API_DEV = "https://api06.dev.openstreetmap.org/api"; 038 private static final String OSM_API_MASTER = "https://master.apis.dev.openstreetmap.org/api"; 039 /** Whether the default parameters are used; one setting for each host, with the setting for all hosts as fallback */ 040 private static final String USE_DEFAULT = "oauth.settings.use-default"; 041 042 private OAuthParameters() { 043 // Hide constructor 044 } 045 046 /** 047 * Replies a set of default parameters for a consumer accessing the standard OSM server 048 * at {@link IUrls#getDefaultOsmApiUrl}. 049 * <p> 050 * Note that this may make network requests for RFC 8414 compliant endpoints. 051 * @return a set of default parameters 052 */ 053 public static IOAuthParameters createDefault() { 054 return createDefault(Config.getUrls().getDefaultOsmApiUrl(), OAuthVersion.OAuth20); 055 } 056 057 /** 058 * Replies a set of default parameters for a consumer accessing an OSM server 059 * at the given API url. URL parameters are only set if the URL equals {@link IUrls#getDefaultOsmApiUrl} 060 * or references the domain "dev.openstreetmap.org", otherwise they may be <code>null</code>. 061 * <p> 062 * Note that this may make network requests for RFC 8414 compliant endpoints. 063 * 064 * @param apiUrl The API URL for which the OAuth default parameters are created. If null or empty, the default OSM API url is used. 065 * @param oAuthVersion The OAuth version to create default parameters for 066 * @return a set of default parameters for the given {@code apiUrl} 067 * @since 18650 068 */ 069 public static IOAuthParameters createDefault(String apiUrl, OAuthVersion oAuthVersion) { 070 if (!Utils.isValidUrl(apiUrl)) { 071 apiUrl = null; 072 } 073 074 switch (oAuthVersion) { 075 case OAuth20: 076 case OAuth21: // For now, OAuth 2.1 (draft) is just OAuth 2.0 with mandatory extensions, which we implement. 077 return getDefaultOAuth20Parameters(apiUrl); 078 default: 079 throw new IllegalArgumentException("Unknown OAuth version: " + oAuthVersion); 080 } 081 } 082 083 /** 084 * Get the OAuth 2.0 parameters the user entered in the advanced OAuth settings and saved with 085 * {@link IOAuthParameters#rememberPreferences()}, or the parameters of the access token of the server. Until a 086 * token exists, this is the only place a client id for a server not in 087 * {@link #createDefault(String, OAuthVersion)} can come from. 088 * {@link OAuth20Parameters#rememberPreferences()} keys by the host of the API, as the access token is; earlier 089 * versions of JOSM keyed them by the API URL, so callers pass that too. 090 * @param keys The preference key suffixes to try, in order 091 * @return The remembered parameters, or {@code null} if none are saved or they cannot be parsed 092 * @since 19627 093 */ 094 private static IOAuthParameters createFromPreferences(String... keys) { 095 for (String key : keys) { 096 if (Utils.isEmpty(key)) { 097 continue; 098 } 099 final String json = Config.getPref().get("oauth.access-token.parameters." + OAuthVersion.OAuth20 + "." + key, null); 100 if (Utils.isEmpty(json)) { 101 continue; 102 } 103 try { 104 OAuth20Parameters parameters = new OAuth20Parameters(json); 105 if (!Utils.isEmpty(parameters.getClientId())) { 106 return parameters; 107 } 108 } catch (IllegalArgumentException | NullPointerException | JsonParsingException e) { 109 // A preference written by hand, or by an older JOSM with different fields 110 Logging.trace(e); 111 } 112 } 113 return null; 114 } 115 116 /** 117 * Get the preference key under which the OAuth 2.0 parameters for the server of an API are stored. This is the 118 * key of the access token of that server too, see {@link org.openstreetmap.josm.io.auth.CredentialsAgent}. 119 * @param apiUrl The API URL, or the host of the API 120 * @return The preference key 121 * @since 19707 122 */ 123 static String getPreferenceKey(String apiUrl) { 124 return "oauth.access-token.parameters." + OAuthVersion.OAuth20 + "." + getHost(apiUrl); 125 } 126 127 /** 128 * Get the host of an API, which is what the OAuth settings and the access token of a server are stored under. 129 * @param apiUrl The API URL, or the host of the API 130 * @return The host, or {@code apiUrl} itself if it is not a URL (including {@code null}) 131 * @since 19707 132 */ 133 public static String getHost(String apiUrl) { 134 if (Utils.isEmpty(apiUrl)) { 135 return apiUrl; 136 } 137 try { 138 final String host = new URI(apiUrl).getHost(); 139 return host == null ? apiUrl : host; 140 } catch (URISyntaxException e) { 141 Logging.trace(e); 142 return apiUrl; 143 } 144 } 145 146 /** 147 * Determines whether the default OAuth 2.0 parameters are used for the server of an API, that is the ones built 148 * into JOSM or published by the server, rather than the ones the user entered in the advanced OAuth settings. 149 * <p> 150 * This is a setting of each server. Until it is set for a server, the setting earlier versions of JOSM had 151 * for all servers is used. 152 * @param apiUrl The API URL, or the host of the API 153 * @return {@code true} if the default parameters are used 154 * @since 19707 155 */ 156 public static boolean isUseDefault(String apiUrl) { 157 final boolean useDefaultForAll = Config.getPref().getBoolean(USE_DEFAULT, true); 158 if (Utils.isEmpty(apiUrl)) { 159 return useDefaultForAll; 160 } 161 return Config.getPref().getBoolean(USE_DEFAULT + "." + getHost(apiUrl), useDefaultForAll); 162 } 163 164 /** 165 * Sets whether the default OAuth 2.0 parameters are used for the server of an API. 166 * @param apiUrl The API URL, or the host of the API 167 * @param useDefault {@code true} to use the default parameters, {@code false} to use the ones the user entered 168 * @see #isUseDefault(String) 169 * @since 19707 170 */ 171 public static void setUseDefault(String apiUrl, boolean useDefault) { 172 if (!Utils.isEmpty(apiUrl)) { 173 Config.getPref().putBoolean(USE_DEFAULT + "." + getHost(apiUrl), useDefault); 174 } 175 } 176 177 private static JsonObject getRFC8414Parameters(String apiUrl) { 178 HttpClient client = null; 179 try { 180 final URI apiURI = new URI(apiUrl); 181 // keep the port, as for a development server on http://localhost:3000 182 final URL rfc8414URL = new URI(apiURI.getScheme(), null, apiURI.getHost(), apiURI.getPort(), 183 "/.well-known/oauth-authorization-server", null, null).toURL(); 184 client = HttpClient.create(rfc8414URL); 185 HttpClient.Response response = client.connect(); 186 if (response.getResponseCode() == 200) { 187 try (BufferedReader reader = response.getContentReader(); 188 JsonReader jsonReader = Json.createReader(reader)) { 189 JsonStructure structure = jsonReader.read(); 190 if (structure.getValueType() == JsonValue.ValueType.OBJECT) { 191 return structure.asJsonObject(); 192 } 193 } 194 } 195 } catch (JsonParsingException | URISyntaxException | IOException e) { 196 throw new JosmRuntimeException(e); 197 } finally { 198 if (client != null) { 199 client.disconnect(); 200 } 201 } 202 return Json.createObjectBuilder().build(); 203 } 204 205 /** 206 * Get the default OAuth 2.0 parameters 207 * @param apiUrl The API url 208 * @return The default parameters 209 */ 210 private static OAuth20Parameters getDefaultOAuth20Parameters(String apiUrl) { 211 final String clientId; 212 final String clientSecret; 213 final String redirectUri = "http://127.0.0.1:8111/oauth_authorization"; 214 apiUrl = OsmApi.normalizeApiUrl(apiUrl == null ? OsmApi.getOsmApi().getServerUrl() : apiUrl); 215 switch (apiUrl) { 216 case OSM_API_DEV: 217 case OSM_API_MASTER: 218 // This clientId/clientSecret are provided by taylor.smock. Feel free to change if needed, but 219 // do let one of the maintainers with server access know so that they can update the test OAuth 220 // token. 221 clientId = "-QZt6n1btDfqrfJNGUIMZjzcyqTgIV6sy79_W4kmQLM"; 222 // Keep secret for dev apis, just in case we want to test something that needs it. 223 clientSecret = "SWnmRD4AdLO-2-ttHE5TR3eLF2McNf7dh0_Z2WNzJdI"; 224 break; 225 case OSM_API_DEFAULT: 226 clientId = "edPII614Lm0_0zEpc_QzEltA9BUll93-Y-ugRQUoHMI"; 227 // We don't actually use the client secret in our authorization flow. 228 clientSecret = null; 229 break; 230 case "https://www.openhistoricalmap.org/api": 231 case "https://api.openhistoricalmap.org/api": 232 // clientId provided by 1ec5 (Minh Nguyễn) 233 clientId = "Hl5yIhFS-Egj6aY7A35ouLOuZl0EHjj8JJQQ46IO96E"; 234 clientSecret = null; 235 break; 236 case "https://opengeofiction.net/api": 237 case "https://lugus.opengeofiction.net/api": 238 // clientId provided by wangi (Lee Kindness), OpenGeofiction administrator. 239 // lugus is the OpenGeofiction test server. 240 clientId = "dKB9Fb5H4MxrM3I23UFxNCh5VGiAEQ_20gC7WmXnaaY"; 241 clientSecret = null; 242 break; 243 default: 244 clientId = ""; 245 clientSecret = null; 246 } 247 // Check if the server is RFC 8414 compliant 248 try { 249 synchronized (RFC8414_RESPONSES) { 250 final JsonObject data; 251 if (NetworkManager.isOffline(apiUrl)) { 252 data = null; 253 } else { 254 data = RFC8414_RESPONSES.computeIfAbsent(apiUrl, OAuthParameters::getRFC8414Parameters); 255 } 256 if (data == null || data.isEmpty()) { 257 RFC8414_RESPONSES.remove(apiUrl); 258 } else { 259 return parseAuthorizationServerMetadataResponse(clientId, clientSecret, apiUrl, 260 redirectUri, data); 261 } 262 } 263 } catch (JosmRuntimeException e) { 264 if (e.getCause() instanceof URISyntaxException || e.getCause() instanceof IOException 265 || e.getCause() instanceof JsonParsingException) { 266 Logging.trace(e); 267 } else { 268 throw e; 269 } 270 } catch (OAuthException e) { 271 Logging.trace(e); 272 } 273 // Fall back to the endpoints of openstreetmap-website, which is what OSM API servers run 274 return new OAuth20Parameters(clientId, clientSecret, getWebsite(apiUrl) + "/oauth2", apiUrl, redirectUri); 275 } 276 277 /** 278 * Get the website of an OSM API server, where openstreetmap-website has its OAuth 2.0 endpoints: the API URL 279 * without its {@code /api}, except for the default OSM API, which is served from a host of its own. 280 * @param apiUrl The normalized API URL 281 * @return The website URL 282 */ 283 private static String getWebsite(String apiUrl) { 284 if (OSM_API_DEFAULT.equals(apiUrl)) { 285 return Config.getUrls().getOSMWebsite(); 286 } 287 return apiUrl.replaceAll("/api$", ""); 288 } 289 290 /** 291 * Parse the response from <a href="https://www.rfc-editor.org/rfc/rfc8414.html">RFC 8414</a> 292 * (OAuth 2.0 Authorization Server Metadata) 293 * @return The parameters for the server metadata 294 */ 295 private static OAuth20Parameters parseAuthorizationServerMetadataResponse(String clientId, String clientSecret, 296 String apiUrl, String redirectUri, 297 JsonObject serverMetadata) 298 throws OAuthException { 299 final String authorizationEndpoint = serverMetadata.getString("authorization_endpoint", null); 300 final String tokenEndpoint = serverMetadata.getString("token_endpoint", null); 301 // This may also have additional documentation like what the endpoints allow (e.g. scopes, algorithms, etc.) 302 if (authorizationEndpoint == null || tokenEndpoint == null) { 303 throw new OAuth20Exception("Either token endpoint or authorization endpoints are missing"); 304 } 305 return new OAuth20Parameters(clientId, clientSecret, tokenEndpoint, authorizationEndpoint, apiUrl, redirectUri); 306 } 307 308 /** 309 * Replies a set of parameters as defined in the preferences: the parameters of the access token of the server, 310 * otherwise the parameters the user entered, unless the server is set to {@link #isUseDefault(String) use the 311 * default parameters}, otherwise the {@link #createDefault(String, OAuthVersion) default parameters}. 312 * 313 * @param oAuthVersion The OAuth version to use. 314 * @param apiUrl the API URL. Must not be {@code null}. 315 * @return the parameters 316 * @since 18650 317 */ 318 public static IOAuthParameters createFromApiUrl(String apiUrl, OAuthVersion oAuthVersion) { 319 apiUrl = OsmApi.normalizeApiUrl(apiUrl); 320 // We actually need the host 321 final String host = getHost(apiUrl); 322 switch (oAuthVersion) { 323 case OAuth20: 324 case OAuth21: // Right now, OAuth 2.1 will work with our OAuth 2.0 implementation 325 try { 326 IOAuthToken storedToken = CredentialsManager.getInstance().lookupOAuthAccessToken(host); 327 if (storedToken != null) { 328 return storedToken.getParameters(); 329 } 330 } catch (CredentialsAgentException e) { 331 Logging.trace(e); 332 } 333 if (!isUseDefault(apiUrl)) { 334 // the API URL is where earlier versions of JOSM stored them 335 IOAuthParameters remembered = createFromPreferences(host, apiUrl); 336 if (remembered != null) { 337 return remembered; 338 } 339 } 340 // Use the URL as it was given: the host is never a valid URL, so createDefault() would silently 341 // fall back to the API currently configured in the preferences. 342 return createDefault(apiUrl, oAuthVersion); 343 default: 344 throw new IllegalArgumentException("Unknown OAuth version: " + oAuthVersion); 345 } 346 } 347}