Changeset 19707 in josm
- Timestamp:
- 2026-11-26T22:24:37+01:00 (less than one hour ago)
- Location:
- trunk
- Files:
-
- 2 added
- 13 deleted
- 27 edited
-
src/org/openstreetmap/josm/data/Preferences.java (modified) (1 diff)
-
src/org/openstreetmap/josm/data/UserIdentityManager.java (modified) (2 diffs)
-
src/org/openstreetmap/josm/data/oauth/OAuth20Parameters.java (modified) (2 diffs)
-
src/org/openstreetmap/josm/data/oauth/OAuth20Token.java (modified) (1 diff)
-
src/org/openstreetmap/josm/data/oauth/OAuthParameters.java (modified) (9 diffs)
-
src/org/openstreetmap/josm/data/oauth/OsmPrivileges.java (deleted)
-
src/org/openstreetmap/josm/data/oauth/osm/OsmScopes.java (modified) (1 diff)
-
src/org/openstreetmap/josm/gui/ExceptionDialogUtil.java (modified) (3 diffs)
-
src/org/openstreetmap/josm/gui/MainApplication.java (modified) (3 diffs)
-
src/org/openstreetmap/josm/gui/oauth/AbstractAuthorizationUI.java (deleted)
-
src/org/openstreetmap/josm/gui/oauth/AccessTokenInfoPanel.java (deleted)
-
src/org/openstreetmap/josm/gui/oauth/AdvancedOAuthPropertiesPanel.java (modified) (19 diffs)
-
src/org/openstreetmap/josm/gui/oauth/AuthorizationProcedure.java (deleted)
-
src/org/openstreetmap/josm/gui/oauth/FullyAutomaticAuthorizationUI.java (deleted)
-
src/org/openstreetmap/josm/gui/oauth/FullyAutomaticPropertiesPanel.java (deleted)
-
src/org/openstreetmap/josm/gui/oauth/ManualAuthorizationUI.java (deleted)
-
src/org/openstreetmap/josm/gui/oauth/OAuthAuthorizationWizard.java (deleted)
-
src/org/openstreetmap/josm/gui/oauth/OsmPrivilegesPanel.java (deleted)
-
src/org/openstreetmap/josm/gui/oauth/package-info.java (modified) (1 diff)
-
src/org/openstreetmap/josm/gui/preferences/server/AuthenticationPreferencesPanel.java (modified) (8 diffs)
-
src/org/openstreetmap/josm/gui/preferences/server/OAuthAuthenticationPreferencesPanel.java (modified) (21 diffs)
-
src/org/openstreetmap/josm/io/MissingOAuthAccessTokenException.java (modified) (5 diffs)
-
src/org/openstreetmap/josm/io/OsmConnection.java (modified) (6 diffs)
-
src/org/openstreetmap/josm/io/auth/JosmPreferencesCredentialAgent.java (modified) (2 diffs)
-
src/org/openstreetmap/josm/tools/ExceptionUtil.java (modified) (1 diff)
-
test/unit/org/openstreetmap/josm/data/PreferencesTest.java (modified) (2 diffs)
-
test/unit/org/openstreetmap/josm/data/UserIdentityManagerTest.java (modified) (2 diffs)
-
test/unit/org/openstreetmap/josm/data/oauth/OAuthParametersTest.java (modified) (5 diffs)
-
test/unit/org/openstreetmap/josm/data/oauth/OsmPrivilegesTest.java (deleted)
-
test/unit/org/openstreetmap/josm/gui/ExceptionDialogUtilTest.java (modified) (3 diffs)
-
test/unit/org/openstreetmap/josm/gui/io/DownloadOpenChangesetsTaskTest.java (modified) (3 diffs)
-
test/unit/org/openstreetmap/josm/gui/oauth/AdvancedOAuthPropertiesPanelTest.java (added)
-
test/unit/org/openstreetmap/josm/gui/oauth/FullyAutomaticAuthorizationUITest.java (deleted)
-
test/unit/org/openstreetmap/josm/gui/oauth/FullyAutomaticPropertiesPanelTest.java (deleted)
-
test/unit/org/openstreetmap/josm/gui/oauth/ManualAuthorizationUITest.java (deleted)
-
test/unit/org/openstreetmap/josm/gui/preferences/server/AuthenticationPreferencesPanelTest.java (added)
-
test/unit/org/openstreetmap/josm/gui/preferences/server/OAuthAuthenticationPreferencesPanelTest.java (modified) (4 diffs)
-
test/unit/org/openstreetmap/josm/io/OsmConnectionTest.java (modified) (7 diffs)
-
test/unit/org/openstreetmap/josm/io/auth/JosmPreferencesCredentialAgentTest.java (modified) (3 diffs)
-
test/unit/org/openstreetmap/josm/testutils/JOSMTestRules.java (modified) (2 diffs)
-
test/unit/org/openstreetmap/josm/testutils/annotations/JosmDefaults.java (modified) (2 diffs)
-
test/unit/org/openstreetmap/josm/tools/ExceptionUtilTest.java (modified) (2 diffs)
Legend:
- Unmodified
- Added
- Removed
-
trunk/src/org/openstreetmap/josm/data/Preferences.java
r19536 r19707 86 86 /** remove if key equals */ 87 87 private static final String[] OBSOLETE_PREF_KEYS = { 88 // nothing ATM 88 "oauth.access-token.key", // OAuth 1.0a token, unused since OAuth 1.0a was removed (#22810). To remove end of 2027 89 "oauth.access-token.secret", // OAuth 1.0a token, unused since OAuth 1.0a was removed (#22810). To remove end of 2027 89 90 }; 90 91 -
trunk/src/org/openstreetmap/josm/data/UserIdentityManager.java
r19080 r19707 86 86 private String userName; 87 87 private UserInfo userInfo; 88 private boolean accessTokenKeyChanged;89 private boolean accessTokenSecretChanged;90 88 91 89 private UserIdentityManager() { … … 297 295 } 298 296 break; 299 case "oauth.access-token.key": 300 accessTokenKeyChanged = true; 301 break; 302 case "oauth.access-token.secret": 303 accessTokenSecretChanged = true; 304 break; 305 default: // Do nothing 306 if (evt.getKey() != null && evt.getKey().equals("oauth.access-token.parameters.OAuth20." + OsmApi.getOsmApi().getHost())) { 307 accessTokenKeyChanged = true; 308 accessTokenSecretChanged = true; 309 } 310 } 311 // oauth.access-token.parameters.OAuth20.api.openstreetmap.org 312 313 if (accessTokenKeyChanged && accessTokenSecretChanged) { 314 accessTokenKeyChanged = false; 315 accessTokenSecretChanged = false; 316 if (OsmApi.isUsingOAuthAndOAuthSetUp(OsmApi.getOsmApi())) { 317 getInstance().initFromOAuth(); 318 } else if (OsmApi.isUsingOAuth()) { 319 setAnonymous(); 297 default: 298 // the OAuth 2 token of the current server was stored or removed, e.g. oauth.access-token.object.OAuth20.api.openstreetmap.org; 299 // its parameters are kept when it is removed, so they do not tell 300 if (("oauth.access-token.object.OAuth20." + OsmApi.getOsmApi().getHost()).equals(evt.getKey())) { 301 if (OsmApi.isUsingOAuthAndOAuthSetUp(OsmApi.getOsmApi())) { 302 getInstance().initFromOAuth(); 303 } else if (OsmApi.isUsingOAuth()) { 304 setAnonymous(); 305 } 320 306 } 321 307 } -
trunk/src/org/openstreetmap/josm/data/oauth/OAuth20Parameters.java
r19519 r19707 16 16 17 17 import org.openstreetmap.josm.spi.preferences.Config; 18 import org.openstreetmap.josm.tools.Logging; 19 import org.openstreetmap.josm.tools.Utils; 18 20 19 21 /** … … 131 133 } 132 134 135 /** 136 * {@inheritDoc} 137 * <p> 138 * The parameters are stored under the host of the API, where the access token of the server stores its 139 * parameters as well. 140 */ 133 141 @Override 134 142 public void rememberPreferences() { 135 Config.getPref().put("oauth.access-token.parameters." + OAuthVersion.OAuth20 + "." + this.apiUrl, 136 this.toPreferencesString()); 143 if (Utils.isEmpty(this.apiUrl)) { 144 // there is no server to store them for 145 Logging.warn("OAuth parameters of client id {0} have no API URL and are not stored", this.clientId); 146 return; 147 } 148 final String key = OAuthParameters.getPreferenceKey(this.apiUrl); 149 Config.getPref().put(key, this.toPreferencesString()); 150 // earlier versions of JOSM stored them under the API URL 151 final String apiUrlKey = "oauth.access-token.parameters." + OAuthVersion.OAuth20 + "." + this.apiUrl; 152 if (!key.equals(apiUrlKey)) { 153 Config.getPref().put(apiUrlKey, null); 154 } 137 155 } 138 156 -
trunk/src/org/openstreetmap/josm/data/oauth/OAuth20Token.java
r19519 r19707 50 50 public OAuth20Token(IOAuthParameters oauthParameters, String json) throws OAuth20Exception { 51 51 this(oauthParameters, new InputStreamReader(new ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8)), StandardCharsets.UTF_8)); 52 } 53 54 /** 55 * Create a bearer token from the access token alone, such as a token issued outside JOSM and pasted by the user. 56 * It has no refresh token, and works with nothing else: the parameters only need the API URL the token is for. 57 * @param oauthParameters The parameters for the OAuth token 58 * @param accessToken The access token 59 * @return The bearer token 60 * @since 19707 61 */ 62 public static OAuth20Token fromAccessToken(IOAuthParameters oauthParameters, String accessToken) { 63 final String json = Json.createObjectBuilder() 64 .add(ACCESS_TOKEN, accessToken) 65 .add(TOKEN_TYPE, "bearer") 66 .build().toString(); 67 try { 68 return new OAuth20Token(oauthParameters, json); 69 } catch (OAuth20Exception e) { 70 // both required fields are present 71 throw new JosmRuntimeException(e); 72 } 52 73 } 53 74 -
trunk/src/org/openstreetmap/josm/data/oauth/OAuthParameters.java
r19651 r19707 37 37 private static final String OSM_API_DEV = "https://api06.dev.openstreetmap.org/api"; 38 38 private static final String OSM_API_MASTER = "https://master.apis.dev.openstreetmap.org/api"; 39 /** Whether the default parameters are used; one setting for each host, with the setting for all hosts as fallback */ 40 private static final String USE_DEFAULT = "oauth.settings.use-default"; 39 41 40 42 private OAuthParameters() { … … 81 83 /** 82 84 * Get the OAuth 2.0 parameters the user entered in the advanced OAuth settings and saved with 83 * {@link IOAuthParameters#rememberPreferences()}. Until a token exists, this is the only place a 84 * client id for a server not in {@link #createDefault(String, OAuthVersion)} can come from. 85 * {@link OAuth20Parameters#rememberPreferences()} keys by the API URL as given; callers may pass 86 * either the URL or its host, so both are tried. 85 * {@link IOAuthParameters#rememberPreferences()}, or the parameters of the access token of the server. Until a 86 * token exists, this is the only place a client id for a server not in 87 * {@link #createDefault(String, OAuthVersion)} can come from. 88 * {@link OAuth20Parameters#rememberPreferences()} keys by the host of the API, as the access token is; earlier 89 * versions of JOSM keyed them by the API URL, so callers pass that too. 87 90 * @param keys The preference key suffixes to try, in order 88 91 * @return The remembered parameters, or {@code null} if none are saved or they cannot be parsed … … 111 114 } 112 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 113 177 private static JsonObject getRFC8414Parameters(String apiUrl) { 114 178 HttpClient client = null; 115 179 try { 116 180 final URI apiURI = new URI(apiUrl); 117 final URL rfc8414URL = new URI(apiURI.getScheme(), apiURI.getHost(), 118 "/.well-known/oauth-authorization-server", null).toURL(); 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(); 119 184 client = HttpClient.create(rfc8414URL); 120 185 HttpClient.Response response = client.connect(); … … 147 212 final String clientSecret; 148 213 final String redirectUri = "http://127.0.0.1:8111/oauth_authorization"; 149 final String baseUrl;150 214 apiUrl = OsmApi.normalizeApiUrl(apiUrl == null ? OsmApi.getOsmApi().getServerUrl() : apiUrl); 151 215 switch (apiUrl) { … … 181 245 clientSecret = null; 182 246 } 183 baseUrl = apiUrl;184 247 // Check if the server is RFC 8414 compliant 185 248 try { … … 208 271 Logging.trace(e); 209 272 } 210 // Fall back to guessing the parameters. 211 return new OAuth20Parameters(clientId, clientSecret, baseUrl, apiUrl, redirectUri); 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$", ""); 212 288 } 213 289 … … 231 307 232 308 /** 233 * Replies a set of parameters as defined in the preferences. 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}. 234 312 * 235 313 * @param oAuthVersion The OAuth version to use. … … 240 318 public static IOAuthParameters createFromApiUrl(String apiUrl, OAuthVersion oAuthVersion) { 241 319 apiUrl = OsmApi.normalizeApiUrl(apiUrl); 242 final String originalApiUrl = apiUrl;243 320 // We actually need the host 244 if (apiUrl.startsWith("https://") || apiUrl.startsWith("http://")) { 245 try { 246 apiUrl = new URI(apiUrl).getHost(); 247 } catch (URISyntaxException syntaxException) { 248 Logging.trace(apiUrl); 249 } 250 } 321 final String host = getHost(apiUrl); 251 322 switch (oAuthVersion) { 252 323 case OAuth20: 253 324 case OAuth21: // Right now, OAuth 2.1 will work with our OAuth 2.0 implementation 254 325 try { 255 IOAuthToken storedToken = CredentialsManager.getInstance().lookupOAuthAccessToken( apiUrl);326 IOAuthToken storedToken = CredentialsManager.getInstance().lookupOAuthAccessToken(host); 256 327 if (storedToken != null) { 257 328 return storedToken.getParameters(); … … 260 331 Logging.trace(e); 261 332 } 262 IOAuthParameters remembered = createFromPreferences(originalApiUrl, apiUrl); 263 if (remembered != null) { 264 return remembered; 265 } 266 // Use the URL as it was given: apiUrl is the host by now, which is never a valid URL, so 267 // createDefault() would silently fall back to the API currently configured in the preferences. 268 return createDefault(originalApiUrl, oAuthVersion); 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); 269 343 default: 270 344 throw new IllegalArgumentException("Unknown OAuth version: " + oAuthVersion); -
trunk/src/org/openstreetmap/josm/data/oauth/osm/OsmScopes.java
r19519 r19707 21 21 write_gpx, 22 22 /** Modify notes */ 23 write_notes 23 write_notes; 24 25 /** 26 * Get the scopes JOSM requests when it is authorized. An OAuth 2.0 application which JOSM is to use must be 27 * registered with at least these. 28 * @return the scopes, in the order they are requested 29 * @since 19707 30 */ 31 public static OsmScopes[] getJosmScopes() { 32 return new OsmScopes[] {read_gpx, write_gpx, read_prefs, write_prefs, write_api, write_notes}; 33 } 24 34 } -
trunk/src/org/openstreetmap/josm/gui/ExceptionDialogUtil.java
r19216 r19707 16 16 import javax.swing.JOptionPane; 17 17 18 import org.openstreetmap.josm.actions.PreferencesAction; 18 19 import org.openstreetmap.josm.data.osm.OsmPrimitive; 20 import org.openstreetmap.josm.gui.HelpAwareOptionPane.ButtonSpec; 21 import org.openstreetmap.josm.gui.preferences.server.ServerAccessPreference; 19 22 import org.openstreetmap.josm.io.ChangesetClosedException; 20 23 import org.openstreetmap.josm.io.IllegalDataException; … … 26 29 import org.openstreetmap.josm.io.OsmTransferException; 27 30 import org.openstreetmap.josm.tools.ExceptionUtil; 31 import org.openstreetmap.josm.tools.ImageProvider; 28 32 import org.openstreetmap.josm.tools.Logging; 29 33 import org.openstreetmap.josm.tools.bugreport.BugReportExceptionHandler; … … 369 373 */ 370 374 public static void explainMissingOAuthAccessTokenException(MissingOAuthAccessTokenException e) { 371 showErrorDialog( 375 final ButtonSpec[] buttons = { 376 new ButtonSpec(tr("Open preferences"), new ImageProvider("preference"), 377 tr("Open the OSM server preferences, to authorize JOSM or to enter an Access Token"), null), 378 new ButtonSpec(tr("Close"), new ImageProvider("cancel"), tr("Close this message"), null) 379 }; 380 final int answer = HelpAwareOptionPane.showOptionDialog( 381 MainApplication.getMainFrame(), 372 382 ExceptionUtil.explainMissingOAuthAccessTokenException(e), 373 383 tr("Authentication failed"), 384 JOptionPane.ERROR_MESSAGE, 385 null, 386 buttons, 387 buttons[0], 374 388 ht("/ErrorMessages#MissingOAuthAccessToken") 375 389 ); 390 if (answer == 0) { 391 PreferencesAction.forPreferenceTab(tr("Preferences"), null, ServerAccessPreference.class).run(); 392 } 376 393 } 377 394 -
trunk/src/org/openstreetmap/josm/gui/MainApplication.java
r19264 r19707 120 120 import org.openstreetmap.josm.gui.mappaint.RenderingCLI; 121 121 import org.openstreetmap.josm.gui.mappaint.loader.MapPaintStyleLoader; 122 import org.openstreetmap.josm.gui.oauth.OAuthAuthorizationWizard;123 122 import org.openstreetmap.josm.gui.preferences.ToolbarPreferences; 124 123 import org.openstreetmap.josm.gui.preferences.display.LafPreference; … … 140 139 import org.openstreetmap.josm.io.NetworkManager; 141 140 import org.openstreetmap.josm.io.OnlineResource; 142 import org.openstreetmap.josm.io.OsmConnection;143 141 import org.openstreetmap.josm.io.OsmTransferException; 144 142 import org.openstreetmap.josm.io.auth.AbstractCredentialsAgent; … … 1111 1109 static void setupCallbacks() { 1112 1110 HttpClient.setFactory(Http1Client::new); 1113 OsmConnection.setOAuthAccessTokenFetcher(OAuthAuthorizationWizard::obtainAccessToken);1114 1111 AbstractCredentialsAgent.setCredentialsProvider(CredentialDialog::promptCredentials); 1115 1112 MessageNotifier.setNotifierCallback(MainApplication::notifyNewMessages); -
trunk/src/org/openstreetmap/josm/gui/oauth/AdvancedOAuthPropertiesPanel.java
r19627 r19707 10 10 import java.awt.event.ItemEvent; 11 11 import java.awt.event.ItemListener; 12 import java.util.Objects; 13 import java.util.stream.Collectors; 14 import java.util.stream.Stream; 12 15 13 16 import javax.swing.BorderFactory; 14 17 import javax.swing.JCheckBox; 18 import javax.swing.JComponent; 15 19 import javax.swing.JLabel; 16 20 import javax.swing.JOptionPane; … … 22 26 import org.openstreetmap.josm.data.oauth.OAuthParameters; 23 27 import org.openstreetmap.josm.data.oauth.OAuthVersion; 28 import org.openstreetmap.josm.data.oauth.osm.OsmScopes; 24 29 import org.openstreetmap.josm.gui.HelpAwareOptionPane; 25 30 import org.openstreetmap.josm.gui.HelpAwareOptionPane.ButtonSpec; … … 30 35 import org.openstreetmap.josm.gui.widgets.SelectAllOnFocusGainedDecorator; 31 36 import org.openstreetmap.josm.gui.widgets.VerticallyScrollablePanel; 32 import org.openstreetmap.josm.spi.preferences.Config;33 37 import org.openstreetmap.josm.tools.CheckParameterUtil; 34 38 import org.openstreetmap.josm.tools.ImageProvider; … … 37 41 * Panel allowing the user to setup advanced OAuth parameters: 38 42 * <ul> 39 * <li>C onsumer key</li>40 * <li>C onsumersecret</li>41 * <li>Re quest token URL</li>43 * <li>Client ID</li> 44 * <li>Client secret</li> 45 * <li>Redirect URI</li> 42 46 * <li>Access token URL</li> 43 47 * <li>Authorize URL</li> 44 * <li>OSM login URL</li> 45 * <li>OSM logout URL</li> 48 * <li>Access token, which can be pasted instead of authorizing JOSM</li> 46 49 * </ul> 47 50 * … … 58 61 59 62 private final JCheckBox cbUseDefaults = new JCheckBox(tr("Use default settings")); 60 private final JosmTextField tfC onsumerKey= new JosmTextField();61 private final JosmTextField tfC onsumerSecret = new JosmTextField();62 private final JosmTextField tfRe questTokenURL= new JosmTextField();63 private final JosmTextField tfClientId = new JosmTextField(); 64 private final JosmTextField tfClientSecret = new JosmTextField(); 65 private final JosmTextField tfRedirectUri = new JosmTextField(); 63 66 private final JosmTextField tfAccessTokenURL = new JosmTextField(); 64 67 private final JosmTextField tfAuthoriseURL = new JosmTextField(); 68 private final JLabel lblAccessToken = new JLabel(tr("Access Token:")); 69 private final JosmTextField tfAccessToken = new JosmTextField(); 65 70 private final OAuthVersion oauthVersion; 66 71 private transient UseDefaultItemListener ilUseDefault; … … 88 93 add(cbUseDefaults, gc); 89 94 90 // -- c onsumer key95 // -- client id 91 96 gc.gridy = 1; 92 97 gc.weightx = 0.0; 93 98 gc.gridwidth = 1; 94 add( new JLabel(tr("Client ID:")), gc);95 96 gc.gridx = 1; 97 gc.weightx = 1.0; 98 add(tfC onsumerKey, gc);99 SelectAllOnFocusGainedDecorator.decorate(tfC onsumerKey);100 101 // -- c onsumersecret99 add(label(tr("Client ID:"), tfClientId), gc); 100 101 gc.gridx = 1; 102 gc.weightx = 1.0; 103 add(tfClientId, gc); 104 SelectAllOnFocusGainedDecorator.decorate(tfClientId); 105 106 // -- client secret 102 107 gc.gridy++; 103 108 gc.gridx = 0; 104 109 gc.weightx = 0.0; 105 add( new JLabel(tr("Client Secret:")), gc);106 107 gc.gridx = 1; 108 gc.weightx = 1.0; 109 add(tfC onsumerSecret, gc);110 SelectAllOnFocusGainedDecorator.decorate(tfC onsumerSecret);111 112 // -- re quest token URL110 add(label(tr("Client Secret:"), tfClientSecret), gc); 111 112 gc.gridx = 1; 113 gc.weightx = 1.0; 114 add(tfClientSecret, gc); 115 SelectAllOnFocusGainedDecorator.decorate(tfClientSecret); 116 117 // -- redirect URI 113 118 gc.gridy++; 114 119 gc.gridx = 0; 115 120 gc.weightx = 0.0; 116 add( new JLabel(tr("Redirect URL:")), gc);117 118 gc.gridx = 1; 119 gc.weightx = 1.0; 120 add(tfRe questTokenURL, gc);121 SelectAllOnFocusGainedDecorator.decorate(tfRe questTokenURL);121 add(label(tr("Redirect URL:"), tfRedirectUri), gc); 122 123 gc.gridx = 1; 124 gc.weightx = 1.0; 125 add(tfRedirectUri, gc); 126 SelectAllOnFocusGainedDecorator.decorate(tfRedirectUri); 122 127 123 128 // -- access token URL … … 125 130 gc.gridx = 0; 126 131 gc.weightx = 0.0; 127 add( new JLabel(tr("Access Token URL:")), gc);132 add(label(tr("Access Token URL:"), tfAccessTokenURL), gc); 128 133 129 134 gc.gridx = 1; … … 136 141 gc.gridx = 0; 137 142 gc.weightx = 0.0; 138 add( new JLabel(tr("Authorize URL:")), gc);143 add(label(tr("Authorize URL:"), tfAuthoriseURL), gc); 139 144 140 145 gc.gridx = 1; … … 143 148 SelectAllOnFocusGainedDecorator.decorate(tfAuthoriseURL); 144 149 150 // -- access token: not one of the settings, so it can be pasted whether or not they are the default ones 151 gc.gridy++; 152 gc.gridx = 0; 153 gc.weightx = 0.0; 154 lblAccessToken.setLabelFor(tfAccessToken); 155 add(lblAccessToken, gc); 156 157 gc.gridx = 1; 158 gc.weightx = 1.0; 159 add(tfAccessToken, gc); 160 SelectAllOnFocusGainedDecorator.decorate(tfAccessToken); 161 162 setToolTips(); 163 145 164 ilUseDefault = new UseDefaultItemListener(); 146 165 cbUseDefaults.addItemListener(ilUseDefault); 147 cbUseDefaults.setSelected(Config.getPref().getBoolean("oauth.settings.use-default", true)); 166 cbUseDefaults.setSelected(true); 167 setChildComponentsVisible(false); 148 168 cbUseDefaults.addItemListener(e -> fireParametersChanged()); 149 tfC onsumerKey.getDocument().addDocumentListener(new DocumentListener() {169 tfClientId.getDocument().addDocumentListener(new DocumentListener() { 150 170 @Override 151 171 public void insertUpdate(DocumentEvent e) { … … 165 185 } 166 186 187 /** 188 * Creates the label of a field, which has the tool tip of the field. 189 * @param text the text of the label 190 * @param field the field 191 * @return the label 192 */ 193 private static JLabel label(String text, JosmTextField field) { 194 final JLabel label = new JLabel(text); 195 label.setLabelFor(field); 196 return label; 197 } 198 199 /** 200 * Explains each field, for the fields and their labels. 201 */ 202 private void setToolTips() { 203 final String scopes = Stream.of(OsmScopes.getJosmScopes()).map(Enum::name).collect(Collectors.joining(", ")); 204 cbUseDefaults.setToolTipText(tr("<html>Use the OAuth settings JOSM has built in for this server, or which the server publishes.<br>" 205 + "Untick to enter the settings of an OAuth 2.0 application you registered on the server yourself.</html>")); 206 tfClientId.setToolTipText(tr("<html>The Client ID of an OAuth 2.0 application registered on this server.<br>" 207 + "On an openstreetmap-website server, register one under My Settings > OAuth 2 applications,<br>" 208 + "with the redirect URL below and the permissions {0}.</html>", scopes)); 209 tfClientSecret.setToolTipText(tr("<html>Only needed if the application is registered as confidential.<br>" 210 + "The applications JOSM has built in are public clients and have none.</html>")); 211 tfRedirectUri.setToolTipText(tr("<html>Must be exactly the redirect URL registered with the application.<br>" 212 + "JOSM receives the authorization at {0}, by remote control.</html>", "http://127.0.0.1:8111/oauth_authorization")); 213 tfAccessTokenURL.setToolTipText(tr("<html>Where JOSM gets the Access Token from.<br>" 214 + "Taken from the OAuth metadata of the server if it publishes any; on an openstreetmap-website server,<br>" 215 + "this is the address of the website followed by {0}, not the API URL.</html>", "/oauth2/token")); 216 tfAuthoriseURL.setToolTipText(tr("<html>Where the web browser is sent to authorize JOSM.<br>" 217 + "Taken from the OAuth metadata of the server if it publishes any; on an openstreetmap-website server,<br>" 218 + "this is the address of the website followed by {0}, not the API URL.</html>", "/oauth2/authorize")); 219 tfAccessToken.setToolTipText(tr("<html>The Access Token JOSM uses for this server.<br>" 220 + "A token issued outside JOSM can be pasted here instead of authorizing JOSM; it needs the permissions {0}.</html>", 221 scopes)); 222 for (Component c : getComponents()) { 223 if (c instanceof JLabel && ((JLabel) c).getLabelFor() instanceof JComponent) { 224 ((JLabel) c).setToolTipText(((JComponent) ((JLabel) c).getLabelFor()).getToolTipText()); 225 } 226 } 227 } 228 167 229 private void fireParametersChanged() { 168 230 firePropertyChange(PARAMETERS_CHANGED_PROP, null, null); 231 } 232 233 /** 234 * Get the access token as entered in the panel. 235 * @return the access token, without surrounding white space; empty if there is none 236 * @since 19707 237 */ 238 public String getAccessToken() { 239 return tfAccessToken.getText().trim(); 240 } 241 242 /** 243 * Sets the access token to be displayed. 244 * @param accessToken the access token, or {@code null} if there is none 245 * @since 19707 246 */ 247 public void setAccessToken(String accessToken) { 248 tfAccessToken.setText(accessToken); 169 249 } 170 250 … … 181 261 /** 182 262 * Get the client id as entered in the panel, without falling back to the defaults. 183 * @return the client id field's text 263 * @return the client id field's text, without surrounding white space 184 264 * @since 19627 185 265 */ 186 266 public String getEnteredClientId() { 187 return tfC onsumerKey.getText();267 return tfClientId.getText().trim(); 188 268 } 189 269 190 270 protected boolean hasCustomSettings() { 191 IOAuthParameters params = OAuthParameters.createDefault(apiUrl, OAuthVersion.OAuth20);271 IOAuthParameters params = OAuthParameters.createDefault(apiUrl, this.oauthVersion); 192 272 return !params.equals(getAdvancedParameters()); 193 273 } … … 231 311 case OAuth21: 232 312 OAuth20Parameters params20 = (OAuth20Parameters) iParams; 233 tfC onsumerKey.setText(params20.getClientId());234 tfC onsumerSecret.setText(params20.getClientSecret());313 tfClientId.setText(params20.getClientId()); 314 tfClientSecret.setText(params20.getClientSecret()); 235 315 tfAccessTokenURL.setText(params20.getAccessTokenUrl()); 236 316 tfAuthoriseURL.setText(params20.getAuthorizationUrl()); 237 tfRe questTokenURL.setText(params20.getRedirectUri());317 tfRedirectUri.setText(params20.getRedirectUri()); 238 318 break; 239 319 default: 240 320 throw new UnsupportedOperationException("Unsupported OAuth version: " + this.oauthVersion); 241 321 } 242 setChildComponents Enabled(false);322 setChildComponentsVisible(false); 243 323 }); 244 324 } 245 325 246 protected void setChildComponentsEnabled(boolean enabled) { 326 /** 327 * Shows or hides the OAuth parameters: they are shown when the user enters them, that is when the default 328 * settings are not used. The access token is not one of them, and is always shown. 329 * @param visible {@code true} to show the parameters 330 * @since 19707 331 */ 332 protected void setChildComponentsVisible(boolean visible) { 247 333 for (Component c: getComponents()) { 334 if (c == tfAccessToken || c == lblAccessToken) { 335 continue; 336 } 248 337 if (c instanceof JosmTextField || c instanceof JLabel) { 249 c.setEnabled(enabled); 250 } 251 } 338 c.setVisible(visible); 339 } 340 } 341 revalidate(); 252 342 } 253 343 … … 260 350 if (cbUseDefaults.isSelected()) 261 351 return OAuthParameters.createDefault(apiUrl, this.oauthVersion); 352 return getDisplayedParameters(); 353 } 354 355 /** 356 * Replies the OAuth parameters as currently displayed in this properties panel: the default ones are shown when 357 * "use default settings" is ticked, as far as they are known yet. Unlike {@link #getAdvancedParameters()}, this 358 * never makes a network request, and some of the parameters may be empty. White space around the values, which 359 * is easily copied along with them, is left out: a client secret with a trailing space is refused by the server. 360 * 361 * @return the OAuth parameters 362 * @since 19707 363 */ 364 public OAuth20Parameters getDisplayedParameters() { 262 365 return new OAuth20Parameters( 263 tfC onsumerKey.getText(),264 tfC onsumerSecret.getText(),265 tfAccessTokenURL.getText(), 266 tfAuthoriseURL.getText(), 366 tfClientId.getText().trim(), 367 tfClientSecret.getText().trim(), 368 tfAccessTokenURL.getText().trim(), 369 tfAuthoriseURL.getText().trim(), 267 370 apiUrl, 268 tfRe questTokenURL.getText()371 tfRedirectUri.getText().trim() 269 372 ); 270 373 } … … 280 383 if (parameters.equals(OAuthParameters.createDefault(apiUrl, parameters.getOAuthVersion()))) { 281 384 cbUseDefaults.setSelected(true); 282 setChildComponents Enabled(false);385 setChildComponentsVisible(false); 283 386 } else { 284 387 cbUseDefaults.setSelected(false); 285 setChildComponents Enabled(true);388 setChildComponentsVisible(true); 286 389 if (parameters instanceof OAuth20Parameters) { 287 390 OAuth20Parameters parameters20 = (OAuth20Parameters) parameters; 288 tfC onsumerKey.setText(parameters20.getClientId());289 tfC onsumerSecret.setText(parameters20.getClientSecret());391 tfClientId.setText(parameters20.getClientId()); 392 tfClientSecret.setText(parameters20.getClientSecret()); 290 393 tfAccessTokenURL.setText(parameters20.getAccessTokenUrl()); 291 394 tfAuthoriseURL.setText(parameters20.getAuthorizationUrl()); 292 tfRe questTokenURL.setText(parameters20.getRedirectUri());395 tfRedirectUri.setText(parameters20.getRedirectUri()); 293 396 } 294 397 } … … 303 406 public void initialize(String paramApiUrl) { 304 407 CheckParameterUtil.ensureParameterNotNull(paramApiUrl, "paramApiUrl"); 305 setApiUrl(paramApiUrl); 306 boolean useDefault = Config.getPref().getBoolean("oauth.settings.use-default", true); 408 this.apiUrl = paramApiUrl; 409 // "use default settings" is a setting of each server 410 boolean useDefault = OAuthParameters.isUseDefault(paramApiUrl); 307 411 ilUseDefault.setEnabled(false); 412 cbUseDefaults.setSelected(useDefault); 413 setChildComponentsVisible(!useDefault); 308 414 MainApplication.worker.execute(() -> { 309 415 if (useDefault) { … … 311 417 } else { 312 418 // createFromApiUrl may make a network request 313 final IOAuthParameters parameters = OAuthParameters.createFromApiUrl(paramApiUrl, OAuthVersion.OAuth20);419 final IOAuthParameters parameters = OAuthParameters.createFromApiUrl(paramApiUrl, this.oauthVersion); 314 420 GuiHelper.runInEDT(() -> setAdvancedParameters(parameters)); 315 421 } … … 319 425 320 426 /** 321 * Remembers the current values in the preferences <code>pref</code>. 427 * Remembers the current values in the preferences <code>pref</code>: whether the server uses the default 428 * settings, and the settings entered if not. Settings entered earlier are kept when the default settings are 429 * used, so that they are there again when they are needed again. 322 430 */ 323 431 public void rememberPreferences() { 324 Config.getPref().putBoolean("oauth.settings.use-default", cbUseDefaults.isSelected()); 325 if (cbUseDefaults.isSelected()) { 326 MainApplication.worker.execute(() -> OAuthParameters.createDefault().rememberPreferences()); 327 } else { 432 if (apiUrl == null) { 433 return; // not initialized 434 } 435 OAuthParameters.setUseDefault(apiUrl, cbUseDefaults.isSelected()); 436 if (!cbUseDefaults.isSelected()) { 328 437 getAdvancedParameters().rememberPreferences(); 329 438 } … … 345 454 break; 346 455 case ItemEvent.DESELECTED: 347 setChildComponents Enabled(true);456 setChildComponentsVisible(true); 348 457 break; 349 458 default: // Do nothing … … 363 472 */ 364 473 public void setApiUrl(String apiUrl) { 474 if (this.apiUrl != null && apiUrl != null 475 && !Objects.equals(OAuthParameters.getHost(this.apiUrl), OAuthParameters.getHost(apiUrl))) { 476 // another server, with settings of its own 477 initialize(apiUrl); 478 return; 479 } 365 480 this.apiUrl = apiUrl; 366 481 if (cbUseDefaults.isSelected()) { -
trunk/src/org/openstreetmap/josm/gui/oauth/package-info.java
r8624 r19707 2 2 3 3 /** 4 * Provides GUI classes for handling OAuth authentication to OSM API. 5 * Backend is <a href="https://github.com/mttkay/signpost">OAuth Signpost</a>. 4 * Provides GUI classes for handling OAuth 2.0 authentication to the OSM API. 6 5 */ 7 6 package org.openstreetmap.josm.gui.oauth; -
trunk/src/org/openstreetmap/josm/gui/preferences/server/AuthenticationPreferencesPanel.java
r19095 r19707 18 18 import javax.swing.JRadioButton; 19 19 20 import org.openstreetmap.josm.actions.ExpertToggleAction; 20 21 import org.openstreetmap.josm.data.UserIdentityManager; 21 22 import org.openstreetmap.josm.data.oauth.OAuthAccessTokenHolder; … … 36 37 public class AuthenticationPreferencesPanel extends VerticallyScrollablePanel implements PropertyChangeListener { 37 38 39 /** the choice of the authentication method; only shown to experts, see {@link #updateAuthenticationMethodVisibility()} */ 40 private final JPanel pnlAuthenticationMethod = new JPanel(new FlowLayout(FlowLayout.LEADING)); 41 /** follows expert mode; held here since {@link ExpertToggleAction} only keeps a weak reference to its listeners */ 42 private final transient ExpertToggleAction.ExpertModeChangeListener expertModeListener = 43 isExpert -> updateAuthenticationMethodVisibility(); 38 44 /** indicates whether we use basic authentication */ 39 45 private final JRadioButton rbBasicAuthentication = new JRadioButton(); … … 64 70 AuthenticationMethodChangeListener authChangeListener = new AuthenticationMethodChangeListener(); 65 71 66 JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.LEADING));67 72 // -- radio button for basic authentication 68 buttonPanel.add(rbBasicAuthentication);73 pnlAuthenticationMethod.add(rbBasicAuthentication); 69 74 rbBasicAuthentication.setText(tr("Use Basic Authentication")); 70 75 rbBasicAuthentication.setToolTipText(tr("Select to use HTTP basic authentication with your OSM username and password")); 71 76 rbBasicAuthentication.addItemListener(authChangeListener); 72 77 //-- radio button for OAuth 2.0 73 buttonPanel.add(rbOAuth20);78 pnlAuthenticationMethod.add(rbOAuth20); 74 79 rbOAuth20.setSelected(true); // This must before adding the listener; otherwise, saveToPreferences is called prior to initFromPreferences 75 80 rbOAuth20.setText(tr("Use OAuth {0}", "2.0")); … … 77 82 rbOAuth20.addItemListener(authChangeListener); 78 83 79 add(buttonPanel, GBC.eol()); 84 add(pnlAuthenticationMethod, GBC.eol()); 85 ExpertToggleAction.addExpertModeChangeListener(expertModeListener); 80 86 //-- radio button for OAuth 81 87 ButtonGroup bg = new ButtonGroup(); … … 120 126 pnlBasicAuthPreferences.initFromPreferences(); 121 127 pnlOAuth20Preferences.initFromPreferences(); 128 updateAuthenticationMethodVisibility(); 129 } 130 131 /** 132 * Shows the choice of the authentication method in expert mode only, since basic authentication is meant as a 133 * quick way to test one's own server rather than for normal use. It is shown regardless while basic 134 * authentication is selected, so that a profile using it does not lose sight of its own setting. Selecting 135 * another method does not hide the choice straight away, which would take the option away under the mouse. 136 */ 137 private void updateAuthenticationMethodVisibility() { 138 pnlAuthenticationMethod.setVisible(ExpertToggleAction.isExpert() || rbBasicAuthentication.isSelected()); 122 139 } 123 140 … … 133 150 authMethod = "oauth20"; 134 151 } else { 135 throw new IllegalStateException("One of OAuth 2.0 , OAuth 1.0a,or Basic authentication must be checked");152 throw new IllegalStateException("One of OAuth 2.0 or Basic authentication must be checked"); 136 153 } 137 154 final boolean initUser = Config.getPref().put("osm-server.auth-method", authMethod); … … 170 187 } else if (rbOAuth20.isSelected()) { 171 188 pnlAuthenticationParameters.add(pnlOAuth20Preferences, BorderLayout.CENTER); 172 pnlOAuth20Preferences.saveToPreferences();189 // only refresh it: saving here would save what was entered before the user pressed OK 173 190 pnlOAuth20Preferences.initFromPreferences(); 174 191 pnlOAuth20Preferences.revalidate(); … … 189 206 190 207 /** 191 * Update the acceptable authentications methods 208 * Update the acceptable authentications methods: basic authentication is not offered for a server which is known 209 * not to accept it, unless it is in use already, so that it can be changed. 192 210 * @param apiUrl The API url to check 193 211 */ 194 212 private void updateAcceptableAuthenticationMethods(String apiUrl) { 195 213 final String authMethod = OsmApi.getAuthMethod(); 196 final boolean defaultApi = JosmUrls.getInstance().getDefaultOsmApiUrl().equals(apiUrl); 197 rbBasicAuthentication.setEnabled(rbBasicAuthentication.isSelected() || "basic".equals(authMethod) || !defaultApi); 214 rbBasicAuthentication.setEnabled(rbBasicAuthentication.isSelected() || "basic".equals(authMethod) 215 || !isOAuthOnly(apiUrl)); 216 } 217 218 /** 219 * Determines whether a server is known to accept OAuth 2.0 only, not basic authentication. 220 * @param apiUrl The API url to check 221 * @return {@code true} for the default OSM API and the OpenGeofiction API 222 */ 223 private static boolean isOAuthOnly(String apiUrl) { 224 final String url = OsmApi.normalizeApiUrl(apiUrl); 225 return JosmUrls.getInstance().getDefaultOsmApiUrl().equals(url) || "https://opengeofiction.net/api".equals(url); 198 226 } 199 227 -
trunk/src/org/openstreetmap/josm/gui/preferences/server/OAuthAuthenticationPreferencesPanel.java
r19627 r19707 13 13 import java.awt.Insets; 14 14 import java.awt.event.ActionEvent; 15 import java.awt.event.ItemEvent;16 15 import java.beans.PropertyChangeEvent; 17 16 import java.beans.PropertyChangeListener; … … 19 18 import java.net.URISyntaxException; 20 19 import java.util.Arrays; 21 import java.util.Objects;22 20 23 21 import javax.swing.AbstractAction; … … 25 23 import javax.swing.JButton; 26 24 import javax.swing.JCheckBox; 27 import javax.swing.J Label;25 import javax.swing.JOptionPane; 28 26 import javax.swing.JPanel; 29 27 30 import org.openstreetmap.josm. actions.ExpertToggleAction;28 import org.openstreetmap.josm.data.oauth.IOAuthParameters; 31 29 import org.openstreetmap.josm.data.oauth.IOAuthToken; 30 import org.openstreetmap.josm.data.oauth.OAuth20Authorization; 32 31 import org.openstreetmap.josm.data.oauth.OAuth20Token; 33 32 import org.openstreetmap.josm.data.oauth.OAuthAccessTokenHolder; 34 33 import org.openstreetmap.josm.data.oauth.OAuthParameters; 35 34 import org.openstreetmap.josm.data.oauth.OAuthVersion; 35 import org.openstreetmap.josm.data.oauth.osm.OsmScopes; 36 36 import org.openstreetmap.josm.data.validation.routines.DomainValidator; 37 37 import org.openstreetmap.josm.gui.MainApplication; 38 38 import org.openstreetmap.josm.gui.oauth.AdvancedOAuthPropertiesPanel; 39 import org.openstreetmap.josm.gui.oauth.AuthorizationProcedure;40 import org.openstreetmap.josm.gui.oauth.OAuthAuthorizationWizard;41 39 import org.openstreetmap.josm.gui.oauth.TestAccessTokenTask; 42 40 import org.openstreetmap.josm.gui.util.GuiHelper; 43 41 import org.openstreetmap.josm.gui.widgets.JMultilineLabel; 44 import org.openstreetmap.josm.gui.widgets.JosmTextField;45 42 import org.openstreetmap.josm.io.OsmApi; 46 43 import org.openstreetmap.josm.io.auth.CredentialsManager; 44 import org.openstreetmap.josm.io.remotecontrol.RemoteControl; 47 45 import org.openstreetmap.josm.tools.GBC; 48 46 import org.openstreetmap.josm.tools.ImageProvider; 49 47 import org.openstreetmap.josm.tools.Logging; 50 import org.openstreetmap.josm.tools.UserCancelException;51 48 import org.openstreetmap.josm.tools.Utils; 52 49 53 50 /** 54 * The preferences panel for the OAuth 1.0a preferences. This just a summary panel 55 * showing the current Access Token Key and Access Token Secret, if the 56 * user already has an Access Token. 57 * <br> 58 * For initial authorisation see {@link OAuthAuthorizationWizard}. 51 * The preferences panel for OAuth 2.0: whether JOSM has an Access Token for the server, a button to authorize JOSM 52 * in the web browser, and the advanced OAuth parameters, which include the Access Token itself so that a token 53 * obtained outside JOSM can be pasted instead. 59 54 * @since 2745 60 55 */ 61 56 public class OAuthAuthenticationPreferencesPanel extends JPanel implements PropertyChangeListener { 62 57 private final JCheckBox cbUseForAllRequests = new JCheckBox(); 63 private final JCheckBox cbShowAdvancedParameters = new JCheckBox(tr("Display Advanced OAuth Parameters"));64 58 private final JCheckBox cbSaveToPreferences = new JCheckBox(tr("Save to preferences")); 65 59 private final JPanel pnlAuthorisationMessage = new JPanel(new BorderLayout()); … … 94 88 cbUseForAllRequests.setToolTipText(tr("For user-based bandwidth limit instead of IP-based one")); 95 89 pnl.add(cbUseForAllRequests, GBC.eol().fill(GBC.HORIZONTAL)); 96 97 pnl.add(cbShowAdvancedParameters, GBC.eol().fill(GBC.HORIZONTAL));98 cbShowAdvancedParameters.setSelected(false);99 cbShowAdvancedParameters.addItemListener(100 evt -> pnlAdvancedProperties.setVisible(evt.getStateChange() == ItemEvent.SELECTED)101 );102 90 103 91 pnl.add(pnlAdvancedProperties, GBC.eol().fill(GBC.HORIZONTAL).insets(0, 3, 0, 0)); … … 109 97 ) 110 98 ); 111 pnlAdvancedProperties.setVisible(false);112 99 pnlAdvancedProperties.addPropertyChangeListener(this); 113 100 return pnl; … … 119 106 */ 120 107 private void updateAuthoriseNowActions() { 121 for (JPanel panel : Arrays.asList(this.pnlNotYetAuthorised, (JPanel)this.pnlAlreadyAuthorised.getComponent(6))) {108 for (JPanel panel : Arrays.asList(this.pnlNotYetAuthorised, this.pnlAlreadyAuthorised.pnlButtons)) { 122 109 for (Component component : panel.getComponents()) { 123 110 if (component instanceof JButton && ((JButton) component).getAction() instanceof AuthoriseNowAction) { … … 145 132 protected void refreshView() { 146 133 pnlAuthorisationMessage.removeAll(); 134 pnlAdvancedProperties.setAccessToken(getBearerToken()); 147 135 if (OAuthAccessTokenHolder.getInstance().getAccessToken(this.apiUrl, this.oAuthVersion) != null) { 148 136 pnlAuthorisationMessage.add(pnlAlreadyAuthorised, BorderLayout.CENTER); … … 157 145 158 146 /** 147 * Get the bearer token JOSM currently has for the API. 148 * @return the bearer token, or {@code null} if there is none 149 */ 150 private String getBearerToken() { 151 if (apiUrl == null) { 152 return null; 153 } 154 final IOAuthToken token = OAuthAccessTokenHolder.getInstance().getAccessToken(apiUrl, oAuthVersion); 155 return token instanceof OAuth20Token ? ((OAuth20Token) token).getBearerToken() : null; 156 } 157 158 /** 159 * Determines whether the user changed the access token in the advanced OAuth parameters. 160 * @return {@code true} if the access token entered differs from the one JOSM has 161 */ 162 private boolean isAccessTokenEdited() { 163 final String current = getBearerToken(); 164 return apiUrl != null && !pnlAdvancedProperties.getAccessToken().equals(current == null ? "" : current); 165 } 166 167 /** 168 * Get the access token entered in the advanced OAuth parameters: a token issued outside JOSM, pasted instead of 169 * authorizing JOSM. It works with nothing else, so it is a way to authenticate when authorizing JOSM is not 170 * possible. 171 * @return the token, or {@code null} if none is entered 172 */ 173 private IOAuthToken getEnteredAccessToken() { 174 final String entered = pnlAdvancedProperties.getAccessToken(); 175 return entered.isEmpty() ? null : OAuth20Token.fromAccessToken(pnlAdvancedProperties.getDisplayedParameters(), entered); 176 } 177 178 /** 179 * Takes over the access token entered in the advanced OAuth parameters, or removes the token if the field was 180 * cleared. This is done when the preferences are saved, so that cancelling them leaves the token as it was. A 181 * token which was not changed is left as it is, so that for example its refresh token is kept. 182 */ 183 private void applyEnteredAccessToken() { 184 if (isAccessTokenEdited()) { 185 OAuthAccessTokenHolder.getInstance().setAccessToken(apiUrl, getEnteredAccessToken()); 186 } 187 } 188 189 /** 159 190 * Sets the URL of the OSM API for which this panel is currently displaying OAuth properties. 160 191 * … … 180 211 */ 181 212 public void saveToPreferences() { 213 applyEnteredAccessToken(); 182 214 OAuthAccessTokenHolder.getInstance().setSaveToPreferences(cbSaveToPreferences.isSelected()); 183 215 OAuthAccessTokenHolder.getInstance().save(CredentialsManager.getInstance()); … … 209 241 210 242 // Action for authorising now 211 add(new JButton(new AuthoriseNowAction(AuthorizationProcedure.FULLY_AUTOMATIC)), GBC.eol()); 212 JButton authManually = new JButton(new AuthoriseNowAction(AuthorizationProcedure.MANUALLY)); 213 add(authManually, GBC.eol()); 214 ExpertToggleAction.addVisibilitySwitcher(authManually); 243 add(new JButton(new AuthoriseNowAction()), GBC.eol()); 215 244 216 245 // filler - grab remaining space … … 224 253 */ 225 254 private class AlreadyAuthorisedPanel extends JPanel { 226 private final J osmTextField tfAccessTokenKey= new JosmTextField(null, null, 0, false);255 private final JPanel pnlButtons = new JPanel(new FlowLayout(FlowLayout.LEFT)); 227 256 228 257 /** … … 246 275 lbl.setFont(lbl.getFont().deriveFont(Font.PLAIN)); 247 276 248 // -- access token key277 // -- save to preferences; the Access Token itself is shown with the advanced OAuth parameters 249 278 gc.gridy = 1; 250 gc.gridx = 0;251 gc.gridwidth = 1;252 gc.weightx = 0.0;253 add(new JLabel(tr("Access Token Key:")), gc);254 255 gc.gridx = 1;256 gc.weightx = 1.0;257 add(tfAccessTokenKey, gc);258 tfAccessTokenKey.setEditable(false);259 260 // -- access token secret261 gc.gridy = 2;262 gc.gridx = 0;263 gc.gridwidth = 1;264 gc.weightx = 0.0;265 add(new JLabel(tr("Access Token Secret:")), gc);266 267 // -- access token secret268 gc.gridy = 3;269 279 gc.gridx = 0; 270 280 gc.gridwidth = 2; … … 274 284 275 285 // -- action buttons 276 JPanel btns = new JPanel(new FlowLayout(FlowLayout.LEFT)); 277 btns.add(new JButton(new RenewAuthorisationAction(AuthorizationProcedure.FULLY_AUTOMATIC))); 278 btns.add(new JButton(new TestAuthorisationAction())); 279 btns.add(new JButton(new RemoveAuthorisationAction())); 280 gc.gridy = 4; 286 pnlButtons.add(new JButton(new RenewAuthorisationAction())); 287 pnlButtons.add(new JButton(new TestAuthorisationAction())); 288 pnlButtons.add(new JButton(new RemoveAuthorisationAction())); 289 gc.gridy = 2; 281 290 gc.gridx = 0; 282 291 gc.gridwidth = 2; 283 292 gc.weightx = 1.0; 284 add( btns, gc);293 add(pnlButtons, gc); 285 294 286 295 // filler - grab the remaining space 287 gc.gridy = 6;296 gc.gridy = 3; 288 297 gc.fill = GridBagConstraints.BOTH; 289 298 gc.weightx = 1.0; … … 293 302 294 303 protected final void refreshView() { 295 switch (oAuthVersion) {296 case OAuth20:297 case OAuth21:298 String token = "";299 if (apiUrl != null) {300 OAuth20Token bearerToken = (OAuth20Token) OAuthAccessTokenHolder.getInstance().getAccessToken(apiUrl, oAuthVersion);301 token = bearerToken == null ? "" : bearerToken.getBearerToken();302 }303 tfAccessTokenKey.setText(token == null ? "" : token);304 break;305 default:306 }307 304 cbSaveToPreferences.setSelected(OAuthAccessTokenHolder.getInstance().isSaveToPreferences()); 308 305 } … … 310 307 311 308 /** 312 * Action to authorise the current user 309 * Action to authorise the current user: JOSM is authorized in the web browser, with the OAuth parameters 310 * currently shown, and receives an Access Token by remote control. 313 311 */ 314 312 private class AuthoriseNowAction extends AbstractAction { 315 private final AuthorizationProcedure procedure; 316 317 AuthoriseNowAction(AuthorizationProcedure procedure) { 318 this.procedure = procedure; 319 putValue(NAME, tr("{0} ({1})", tr("Authorize now"), procedure.getText())); 320 putValue(SHORT_DESCRIPTION, procedure.getDescription()); 321 if (procedure == AuthorizationProcedure.FULLY_AUTOMATIC) { 322 new ImageProvider("oauth", "oauth-small").getResource().attachImageIcon(this); 323 } 313 /** Counts the updates of the enabled state, so that the result of an earlier one cannot override a later one */ 314 private int updates; 315 316 AuthoriseNowAction() { 317 putValue(NAME, tr("Authorize now")); 318 putValue(SHORT_DESCRIPTION, tr("Authorize JOSM in the web browser to access the OSM server on your behalf, " 319 + "and get an Access Token")); 320 new ImageProvider("oauth", "oauth-small").getResource().attachImageIcon(this); 324 321 updateEnabledState(); 325 322 } 326 323 327 324 void updateEnabledState() { 328 if (procedure == AuthorizationProcedure.MANUALLY) { 329 this.setEnabled(true); 330 } else if (!pnlAdvancedProperties.isUseDefaultSettings()) { 325 final int update = ++updates; 326 if (!pnlAdvancedProperties.isUseDefaultSettings()) { 331 327 // The user supplied the parameters - the client id of an OAuth application they 332 // registered on the server themselves. The wizard is givenexactly these parameters328 // registered on the server themselves. Authorization uses exactly these parameters 333 329 // when the button is pressed, so they decide whether it can be pressed. 334 330 this.setEnabled(!Utils.isEmpty(pnlAdvancedProperties.getEnteredClientId())); … … 342 338 } 343 339 if (DomainValidator.getInstance().isValid(apiURI.getHost())) { 344 // We want to avoid trying to make connection with an invalid URL 340 // We want to avoid trying to make connection with an invalid URL. These are the parameters 341 // authorization uses, see AdvancedOAuthPropertiesPanel.getAdvancedParameters(). 345 342 final String currentApiUrl = apiUrl; 346 343 MainApplication.worker.execute(() -> { 347 final String clientId = OAuthParameters.createFromApiUrl(apiUrl, oAuthVersion).getClientId(); 348 if (Objects.equals(apiUrl, currentApiUrl)) { 349 GuiHelper.runInEDT(() -> this.setEnabled(!Utils.isEmpty(clientId))); 350 } 344 final String clientId = OAuthParameters.createDefault(currentApiUrl, oAuthVersion).getClientId(); 345 GuiHelper.runInEDT(() -> { 346 if (update == updates) { 347 this.setEnabled(!Utils.isEmpty(clientId)); 348 } 349 }); 351 350 }); 352 351 } … … 356 355 @Override 357 356 public void actionPerformed(ActionEvent arg0) { 358 OAuthAuthorizationWizard wizard = new OAuthAuthorizationWizard( 359 OAuthAuthenticationPreferencesPanel.this, 360 procedure, 361 apiUrl, 362 MainApplication.worker, 363 oAuthVersion, 364 pnlAdvancedProperties.getAdvancedParameters() 365 ); 366 try { 367 wizard.showDialog(token -> GuiHelper.runInEDT(OAuthAuthenticationPreferencesPanel.this::refreshView)); 368 } catch (UserCancelException userCancelException) { 369 Logging.trace(userCancelException); 370 return; 357 final String currentApiUrl = apiUrl; 358 final IOAuthParameters parameters = pnlAdvancedProperties.getAdvancedParameters(); 359 // the token is received by remote control, which is started for the time it takes if it is not running 360 final boolean remoteControlIsRunning = Boolean.TRUE.equals(RemoteControl.PROP_REMOTECONTROL_ENABLED.get()); 361 if (!remoteControlIsRunning) { 362 RemoteControl.start(); 371 363 } 372 pnlAdvancedProperties.setAdvancedParameters(wizard.getOAuthParameters()); 373 refreshView(); 364 new OAuth20Authorization().authorize(parameters, token -> { 365 if (!remoteControlIsRunning) { 366 RemoteControl.stop(); 367 } 368 // a failed attempt, e.g. at a new token, leaves the token JOSM has as it is 369 token.ifPresent(t -> { 370 OAuthAccessTokenHolder.getInstance().setAccessToken(currentApiUrl, t); 371 OAuthAccessTokenHolder.getInstance().save(CredentialsManager.getInstance()); 372 }); 373 GuiHelper.runInEDT(() -> { 374 if (!token.isPresent()) { 375 JOptionPane.showMessageDialog(OAuthAuthenticationPreferencesPanel.this, 376 tr("Authentication failed, please check browser for details."), 377 tr("OAuth Authentication Failed"), 378 JOptionPane.ERROR_MESSAGE); 379 } 380 refreshView(); 381 }); 382 }, OsmScopes.getJosmScopes()); 374 383 } 375 384 } … … 394 403 395 404 /** 396 * Launches the OAuthAuthorisationWizardto generate a new Access Token405 * Authorizes JOSM again, to generate a new Access Token 397 406 */ 398 407 private class RenewAuthorisationAction extends AuthoriseNowAction { … … 400 409 * Constructs a new {@code RenewAuthorisationAction}. 401 410 */ 402 RenewAuthorisationAction(AuthorizationProcedure procedure) { 403 super(procedure); 411 RenewAuthorisationAction() { 404 412 putValue(NAME, tr("New Access Token")); 405 413 putValue(SHORT_DESCRIPTION, tr("Click to step through the OAuth authorization process and generate a new Access Token")); 406 new ImageProvider("oauth", "oauth-small").getResource().attachImageIcon(this);407 414 } 408 415 } … … 423 430 @Override 424 431 public void actionPerformed(ActionEvent evt) { 425 IOAuthToken token = OAuthAccessTokenHolder.getInstance().getAccessToken(apiUrl, OAuthVersion.OAuth20); 432 // a token pasted but not saved yet is what the user wants to know about, and none if the field was cleared 433 final IOAuthToken token = isAccessTokenEdited() ? getEnteredAccessToken() 434 : OAuthAccessTokenHolder.getInstance().getAccessToken(apiUrl, oAuthVersion); 435 if (token == null) { 436 JOptionPane.showMessageDialog(OAuthAuthenticationPreferencesPanel.this, 437 tr("There is no Access Token to test."), tr("Test Access Token"), JOptionPane.INFORMATION_MESSAGE); 438 return; 439 } 426 440 TestAccessTokenTask task = new TestAccessTokenTask( 427 441 OAuthAuthenticationPreferencesPanel.this, … … 437 451 if (AdvancedOAuthPropertiesPanel.PARAMETERS_CHANGED_PROP.equals(evt.getPropertyName())) { 438 452 updateAuthoriseNowActions(); 453 439 454 } else if (OsmApiUrlInputPanel.API_URL_PROP.equals(evt.getPropertyName())) { 440 455 setApiUrl((String) evt.getNewValue()); 456 refreshView(); 441 457 } 442 458 } -
trunk/src/org/openstreetmap/josm/io/MissingOAuthAccessTokenException.java
r12470 r19707 7 7 public class MissingOAuthAccessTokenException extends OsmTransferException { 8 8 9 /** the API URL of the server JOSM has no OAuth client id for, so that it could not obtain an access token */ 10 private final String clientIdMissingFor; 11 9 12 /** 10 13 * Constructs a new {@code MissingOAuthAccessTokenException}. … … 12 15 public MissingOAuthAccessTokenException() { 13 16 super(); 17 this.clientIdMissingFor = null; 14 18 } 15 19 … … 22 26 public MissingOAuthAccessTokenException(String message, Throwable cause) { 23 27 super(message, cause); 28 this.clientIdMissingFor = null; 24 29 } 25 30 … … 30 35 public MissingOAuthAccessTokenException(String message) { 31 36 super(message); 37 this.clientIdMissingFor = null; 38 } 39 40 private MissingOAuthAccessTokenException(String message, String clientIdMissingFor) { 41 super(message); 42 this.clientIdMissingFor = clientIdMissingFor; 32 43 } 33 44 … … 39 50 public MissingOAuthAccessTokenException(Throwable cause) { 40 51 super(cause); 52 this.clientIdMissingFor = null; 53 } 54 55 /** 56 * Creates the exception for a server JOSM has no OAuth client id for, so that it cannot obtain an access token: 57 * the user has to enter the client id of an OAuth application registered on the server, or an access token. 58 * @param apiUrl the API URL of the server 59 * @return the exception 60 * @since 19707 61 */ 62 public static MissingOAuthAccessTokenException clientIdMissing(String apiUrl) { 63 return new MissingOAuthAccessTokenException("No OAuth client id for " + apiUrl + ", cannot request a token", apiUrl); 64 } 65 66 /** 67 * Determines whether JOSM has no OAuth client id for the server, which is why it has no access token. 68 * @return {@code true} if the client id is missing 69 * @since 19707 70 */ 71 public boolean isClientIdMissing() { 72 return clientIdMissingFor != null; 73 } 74 75 /** 76 * Get the API URL of the server JOSM has no OAuth client id for. 77 * @return the API URL, or {@code null} unless {@link #isClientIdMissing()} 78 * @since 19707 79 */ 80 public String getClientIdMissingFor() { 81 return clientIdMissingFor; 41 82 } 42 83 } -
trunk/src/org/openstreetmap/josm/io/OsmConnection.java
r19638 r19707 4 4 import static org.openstreetmap.josm.tools.I18n.tr; 5 5 6 import java.lang.reflect.InvocationTargetException;7 6 import java.net.Authenticator.RequestorType; 8 import java.net.URL;9 7 import java.nio.charset.StandardCharsets; 10 8 import java.util.Base64; … … 32 30 import org.openstreetmap.josm.io.remotecontrol.RemoteControl; 33 31 import org.openstreetmap.josm.tools.HttpClient; 34 import org.openstreetmap.josm.tools.JosmRuntimeException;35 32 import org.openstreetmap.josm.tools.Logging; 36 33 import org.openstreetmap.josm.tools.Utils; … … 49 46 protected HttpClient activeConnection; 50 47 protected IOAuthParameters oAuth20Parameters; 51 52 /**53 * Retrieves OAuth access token.54 * @since 1280355 */56 @FunctionalInterface57 public interface OAuthAccessTokenFetcher {58 /**59 * Obtains an OAuth access token for the connection. Afterwards, the token is accessible via {@link OAuthAccessTokenHolder}.60 * @param serverUrl the URL to OSM server61 * @throws InterruptedException if we're interrupted while waiting for the event dispatching thread to finish OAuth authorization task62 * @throws InvocationTargetException if an exception is thrown while running OAuth authorization task63 */64 void obtainAccessToken(URL serverUrl) throws InvocationTargetException, InterruptedException;65 }66 67 static volatile OAuthAccessTokenFetcher fetcher = u -> {68 throw new JosmRuntimeException("OsmConnection.setOAuthAccessTokenFetcher() has not been called");69 };70 71 /**72 * Sets the OAuth access token fetcher.73 * @param tokenFetcher new OAuth access token fetcher. Cannot be null74 * @since 1280375 */76 public static void setOAuthAccessTokenFetcher(OAuthAccessTokenFetcher tokenFetcher) {77 fetcher = Objects.requireNonNull(tokenFetcher, "tokenFetcher");78 }79 48 80 49 /** … … 150 119 if (Utils.isEmpty(this.oAuth20Parameters.getClientId())) { 151 120 // 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"); 121 // parameter: client_id", so do not send the user to the browser at all, but tell them what is missing. 122 throw MissingOAuthAccessTokenException.clientIdMissing(OsmApi.getOsmApi().getServerUrl()); 157 123 } 158 124 if (!Boolean.TRUE.equals(GuiHelper.runInEDTAndWaitAndReturn(() -> … … 180 146 }; 181 147 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++; 148 consumer, OsmScopes.getJosmScopes()); 149 // Only wait at most 5 minutes for the user to authorize JOSM in the web browser 150 try { 151 if (!done.await(5, TimeUnit.MINUTES)) { 152 Logging.warn("No OAuth access token received from {0} within 5 minutes", OsmApi.getOsmApi().getServerUrl()); 153 } 154 } catch (InterruptedException e) { 155 Thread.currentThread().interrupt(); 156 Logging.trace(e); 157 consumer.accept(Optional.empty()); 158 throw new MissingOAuthAccessTokenException(e); 199 159 } 200 160 } … … 210 170 protected void addOAuth20AuthorizationHeader(HttpClient connection) throws OsmTransferException { 211 171 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. 172 // Look them up with the API URL and not with the host of the request: OAuthParameters.createFromApiUrl() 173 // reduces it to the host itself for the stored parameters, and needs the URL for the default ones. 215 174 this.oAuth20Parameters = OAuthParameters.createFromApiUrl(OsmApi.getOsmApi().getServerUrl(), OAuthVersion.OAuth20); 216 175 } 217 176 OAuthAccessTokenHolder holder = OAuthAccessTokenHolder.getInstance(); 218 177 IOAuthToken token = holder.getAccessToken(connection.getURL().toExternalForm(), OAuthVersion.OAuth20); 219 if (token == null) { 178 // A token is obtained for the API, and so is only found for requests to the host of the API 179 if (token == null && Objects.equals(connection.getURL().getHost(), OsmApi.getOsmApi().getHost())) { 220 180 obtainOAuth20Token(); 221 181 token = holder.getAccessToken(connection.getURL().toExternalForm(), OAuthVersion.OAuth20); 222 182 } 223 if (token == null) { // check if wizardcompleted183 if (token == null) { // check if authorization completed 224 184 throw new MissingOAuthAccessTokenException(); 225 185 } -
trunk/src/org/openstreetmap/josm/io/auth/JosmPreferencesCredentialAgent.java
r19652 r19707 133 133 Set<String> keySet = new HashSet<>(Config.getPref().getKeySet()); 134 134 keySet.addAll(Config.getPref().getSensitive()); // Just in case we decide to not return sensitive keys in getKeySet 135 // Assume we want to remove all access tokens 135 // Assume we want to remove all access tokens. The parameters stay: they are also the OAuth settings the 136 // user entered for the server, which are needed to obtain the next token. 136 137 for (OAuthVersion oauthType : OAuthVersion.values()) { 137 138 final String hostKey = "oauth.access-token.object." + oauthType + "." + host; 138 final String parametersKey = "oauth.access-token.parameters." + oauthType + "." + host;139 139 if (keySet.contains(hostKey)) { 140 140 Config.getPref().removeSensitive(hostKey); 141 }142 if (keySet.contains(parametersKey)) {143 Config.getPref().removeSensitive(parametersKey);144 141 } 145 142 } … … 147 144 final String hostKey = "oauth.access-token.object." + accessToken.getOAuthType() + "." + host; 148 145 final String parametersKey = "oauth.access-token.parameters." + accessToken.getOAuthType() + "." + host; 146 // the parameters first: listeners of the token, like UserIdentityManager, find them in place 147 Config.getPref().put(parametersKey, accessToken.getParameters().toPreferencesString()); 148 Config.getPref().addSensitive(this, parametersKey); 149 149 Config.getPref().put(hostKey, accessToken.toPreferencesString()); 150 Config.getPref().put(parametersKey, accessToken.getParameters().toPreferencesString());151 150 Config.getPref().addSensitive(this, hostKey); 152 Config.getPref().addSensitive(this, parametersKey);153 151 } 154 152 } -
trunk/src/org/openstreetmap/josm/tools/ExceptionUtil.java
r19225 r19707 84 84 public static String explainMissingOAuthAccessTokenException(MissingOAuthAccessTokenException e) { 85 85 Logging.error(e); 86 if (e.isClientIdMissing()) { 87 return tr( 88 "<html>Failed to authenticate at the OSM server ''{0}''.<br>" 89 + "JOSM cannot obtain an OAuth Access Token for this server, because it has no OAuth Client ID for it.<br>" 90 + "Please register an OAuth 2.0 application on the server, and enter its Client ID in the OAuth<br>" 91 + "settings of the Preferences Dialog; or enter an Access Token obtained outside JOSM there." 92 + "</html>", 93 e.getClientIdMissingFor() 94 ); 95 } 86 96 return tr( 87 97 "<html>Failed to authenticate at the OSM server ''{0}''.<br>" -
trunk/test/unit/org/openstreetmap/josm/data/PreferencesTest.java
r18870 r19707 3 3 4 4 import static org.junit.jupiter.api.Assertions.assertEquals; 5 import static org.junit.jupiter.api.Assertions.assertNull; 6 7 import java.io.File; 8 import java.io.IOException; 9 import java.nio.charset.StandardCharsets; 10 import java.nio.file.Files; 11 import java.nio.file.Path; 12 13 import javax.xml.stream.XMLStreamException; 5 14 6 15 import org.junit.jupiter.api.Test; 16 import org.junit.jupiter.api.io.TempDir; 17 import org.openstreetmap.josm.spi.preferences.IBaseDirectories; 7 18 import org.openstreetmap.josm.testutils.annotations.BasicPreferences; 8 19 import org.openstreetmap.josm.testutils.annotations.OsmApi; 20 import org.xml.sax.SAXException; 9 21 10 22 /** … … 26 38 Preferences.main().toXML(true)); 27 39 } 40 41 /** 42 * The OAuth 1.0a access token, which nothing has used since OAuth 1.0a was removed, is deleted from the 43 * preferences when they are loaded, so that it does not stay on disk indefinitely. 44 * @param dir a temporary directory for the preferences file 45 * @throws IOException if the preferences file cannot be written or read 46 * @throws SAXException if the preferences file is not valid 47 * @throws XMLStreamException if the preferences file cannot be parsed 48 */ 49 @Test 50 void testObsoleteOAuth10aTokenIsRemoved(@TempDir Path dir) throws IOException, SAXException, XMLStreamException { 51 Files.write(dir.resolve("preferences.xml"), String.format( 52 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>%n" + 53 "<preferences xmlns='http://josm.openstreetmap.de/preferences-1.0' version='19000'>%n" + 54 " <tag key='oauth.access-token.key' value='an-old-key'/>%n" + 55 " <tag key='oauth.access-token.secret' value='an-old-secret'/>%n" + 56 " <tag key='osm-server.url' value='http://fake.xxx/api'/>%n" + 57 "</preferences>%n").getBytes(StandardCharsets.UTF_8)); 58 final File directory = dir.toFile(); 59 final Preferences preferences = new Preferences(new IBaseDirectories() { 60 @Override 61 public File getPreferencesDirectory(boolean createIfMissing) { 62 return directory; 63 } 64 65 @Override 66 public File getUserDataDirectory(boolean createIfMissing) { 67 return directory; 68 } 69 70 @Override 71 public File getCacheDirectory(boolean createIfMissing) { 72 return directory; 73 } 74 }); 75 preferences.load(); 76 77 assertNull(preferences.get("oauth.access-token.key", null)); 78 assertNull(preferences.get("oauth.access-token.secret", null)); 79 assertEquals("http://fake.xxx/api", preferences.get("osm-server.url", null)); 80 } 28 81 } -
trunk/test/unit/org/openstreetmap/josm/data/UserIdentityManagerTest.java
r18037 r19707 14 14 import java.util.stream.Stream; 15 15 16 import org.openstreetmap.josm.data.oauth.OAuth20Parameters; 17 import org.openstreetmap.josm.data.oauth.OAuth20Token; 18 import org.openstreetmap.josm.data.oauth.OAuthAccessTokenHolder; 16 19 import org.openstreetmap.josm.data.osm.User; 17 20 import org.openstreetmap.josm.data.osm.UserInfo; 21 import org.openstreetmap.josm.io.NetworkManager; 22 import org.openstreetmap.josm.io.OnlineResource; 23 import org.openstreetmap.josm.io.OsmApi; 24 import org.openstreetmap.josm.io.auth.CredentialsManager; 18 25 import org.openstreetmap.josm.spi.preferences.Config; 19 26 import org.openstreetmap.josm.testutils.annotations.BasicPreferences; … … 39 46 userInfo.setDescription(description); 40 47 return userInfo; 48 } 49 50 /** 51 * Removing the OAuth token of the server makes the user anonymous. 52 * <p> 53 * Non-regression test: the identity followed the parameters stored with the token, which are kept since they 54 * are the OAuth settings of the server too, so the user stayed identified after "Remove token". 55 * @throws Exception if the token cannot be stored 56 */ 57 @Test 58 void testRemovingTheOAuthTokenMakesTheUserAnonymous() throws Exception { 59 // fetching the user details once a token is stored must not make a network request 60 NetworkManager.setOffline(OnlineResource.ALL); 61 Config.getPref().put("osm-server.auth-method", "oauth20"); 62 final String apiUrl = OsmApi.getOsmApi().getServerUrl(); 63 final String host = OsmApi.getOsmApi().getHost(); 64 try { 65 OAuthAccessTokenHolder.getInstance().clear(); 66 CredentialsManager.getInstance().storeOAuthAccessToken(host, new OAuth20Token( 67 new OAuth20Parameters("", null, "", "", apiUrl, ""), "{\"access_token\": \"a-token\", \"token_type\": \"bearer\"}")); 68 UserIdentityManager.getInstance().setPartiallyIdentified("a-user"); 69 70 // what "Remove token" in the preferences does 71 OAuthAccessTokenHolder.getInstance().setAccessToken(apiUrl, null); 72 OAuthAccessTokenHolder.getInstance().save(CredentialsManager.getInstance()); 73 74 assertTrue(UserIdentityManager.getInstance().isAnonymous()); 75 } finally { 76 Config.getPref().removeSensitive("oauth.access-token.parameters.OAuth20." + host); 77 Config.getPref().put("osm-server.auth-method", null); 78 OAuthAccessTokenHolder.getInstance().clear(); 79 NetworkManager.setOnline(OnlineResource.ALL); 80 UserIdentityManager.getInstance().setAnonymous(); 81 } 41 82 } 42 83 -
trunk/test/unit/org/openstreetmap/josm/data/oauth/OAuthParametersTest.java
r19638 r19707 3 3 4 4 import static org.junit.jupiter.api.Assertions.assertEquals; 5 import static org.junit.jupiter.api.Assertions.assertFalse; 5 6 import static org.junit.jupiter.api.Assertions.assertNotEquals; 6 7 import static org.junit.jupiter.api.Assertions.assertNotNull; 8 import static org.junit.jupiter.api.Assertions.assertNull; 9 import static org.junit.jupiter.api.Assertions.assertTrue; 7 10 8 11 import org.junit.jupiter.api.AfterEach; … … 15 18 import org.openstreetmap.josm.tools.Logging; 16 19 20 import com.github.tomakehurst.wiremock.WireMockServer; 21 import com.github.tomakehurst.wiremock.client.WireMock; 22 import com.github.tomakehurst.wiremock.core.WireMockConfiguration; 23 17 24 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; 18 25 import nl.jqno.equalsverifier.EqualsVerifier; … … 24 31 class OAuthParametersTest { 25 32 33 private static final String THIRD_PARTY = "https://nonprod-mapops.example.org/api"; 34 private static final String THIRD_PARTY_HOST = "nonprod-mapops.example.org"; 35 private static final String OHM = "https://api.openhistoricalmap.org/api"; 36 private static final String REDIRECT_URI = "http://127.0.0.1:8111/oauth_authorization"; 37 26 38 @AfterEach 27 39 void tearDown() { 28 40 NetworkManager.setOnline(OnlineResource.ALL); 29 // the API URL isstatic state shared with the other tests of this class41 // the preferences are static state shared with the other tests of this class 30 42 Config.getPref().put("osm-server.url", null); 43 for (String key : new String[] {THIRD_PARTY_HOST, THIRD_PARTY, "api.openhistoricalmap.org"}) { 44 Config.getPref().put("oauth.access-token.parameters.OAuth20." + key, null); 45 Config.getPref().put("oauth.settings.use-default." + key, null); 46 } 47 Config.getPref().put("oauth.settings.use-default", null); 48 } 49 50 private static OAuth20Parameters enteredParameters(String apiUrl, String clientId) { 51 return new OAuth20Parameters(clientId, null, apiUrl, apiUrl, REDIRECT_URI); 52 } 53 54 private static String clientIdOf(String apiUrl) { 55 return OAuthParameters.createFromApiUrl(apiUrl, OAuthVersion.OAuth20).getClientId(); 31 56 } 32 57 … … 52 77 assertEquals("", OAuthParameters.createFromApiUrl(thirdParty, OAuthVersion.OAuth20).getClientId()); 53 78 54 // once the parameters are remembered - as the authentication preferences do, under the API URL - they 55 // are found both by the API URL and by the host, which is what a connection has at hand 79 // once the parameters are remembered - as the authentication preferences do - they are found both by the 80 // API URL and by the host, which is what a connection has at hand 81 OAuthParameters.setUseDefault(thirdParty, false); 56 82 new OAuth20Parameters("entered-client-id", null, thirdParty, thirdParty, "http://127.0.0.1:8111/oauth_authorization") 57 83 .rememberPreferences(); … … 60 86 assertEquals("https://api.openhistoricalmap.org/api", 61 87 OAuthParameters.createFromApiUrl("https://api.openhistoricalmap.org/api", OAuthVersion.OAuth20).getApiUrl()); 88 } 89 90 /** 91 * The parameters the user entered are stored under the host of the API, which is where the access token of the 92 * server is stored too, and replace those stored under the API URL by earlier versions of JOSM. 93 */ 94 @Test 95 void testParametersAreStoredUnderTheHost() { 96 NetworkManager.setOffline(OnlineResource.ALL); 97 OAuthParameters.setUseDefault(THIRD_PARTY, false); 98 // as stored by earlier versions of JOSM, which are still found 99 Config.getPref().put("oauth.access-token.parameters.OAuth20." + THIRD_PARTY, 100 enteredParameters(THIRD_PARTY, "old-client-id").toPreferencesString()); 101 assertEquals("old-client-id", clientIdOf(THIRD_PARTY)); 102 103 enteredParameters(THIRD_PARTY, "new-client-id").rememberPreferences(); 104 assertNotNull(Config.getPref().get("oauth.access-token.parameters.OAuth20." + THIRD_PARTY_HOST, null)); 105 assertNull(Config.getPref().get("oauth.access-token.parameters.OAuth20." + THIRD_PARTY, null), 106 "the parameters stored by earlier versions of JOSM are left behind"); 107 assertEquals("new-client-id", clientIdOf(THIRD_PARTY)); 108 assertEquals("new-client-id", clientIdOf(THIRD_PARTY_HOST)); 109 } 110 111 /** 112 * "Use default settings" is a setting of each server: entering the client id of one server does not take the 113 * client ids JOSM has for the other servers away, and the entered parameters are not used once the server is set 114 * to use the default settings again, but stay for when they are needed again. 115 */ 116 @Test 117 void testUseDefaultIsASettingOfEachServer() { 118 NetworkManager.setOffline(OnlineResource.ALL); 119 assertTrue(OAuthParameters.isUseDefault(THIRD_PARTY)); 120 OAuthParameters.setUseDefault(THIRD_PARTY, false); 121 enteredParameters(THIRD_PARTY, "entered-client-id").rememberPreferences(); 122 enteredParameters(OHM, "not-used").rememberPreferences(); 123 124 assertFalse(OAuthParameters.isUseDefault(THIRD_PARTY)); 125 assertFalse(OAuthParameters.isUseDefault(THIRD_PARTY_HOST)); 126 assertTrue(OAuthParameters.isUseDefault(OHM)); 127 assertEquals("entered-client-id", clientIdOf(THIRD_PARTY)); 128 assertEquals("Hl5yIhFS-Egj6aY7A35ouLOuZl0EHjj8JJQQ46IO96E", clientIdOf(OHM)); 129 130 OAuthParameters.setUseDefault(THIRD_PARTY, true); 131 assertEquals("", clientIdOf(THIRD_PARTY)); 132 OAuthParameters.setUseDefault(THIRD_PARTY, false); 133 assertEquals("entered-client-id", clientIdOf(THIRD_PARTY)); 134 } 135 136 /** 137 * Until a server has a "use default settings" of its own, the setting earlier versions of JOSM had for all 138 * servers applies, so that the parameters entered with them are still used. 139 */ 140 @Test 141 void testUseDefaultFallsBackToTheSettingForAllServers() { 142 Config.getPref().putBoolean("oauth.settings.use-default", false); 143 assertFalse(OAuthParameters.isUseDefault(THIRD_PARTY)); 144 OAuthParameters.setUseDefault(THIRD_PARTY, true); 145 assertTrue(OAuthParameters.isUseDefault(THIRD_PARTY)); 146 assertFalse(OAuthParameters.isUseDefault(OHM)); 147 } 148 149 /** 150 * The OAuth settings of a server are stored under its host, whether it is given as the API URL or as the host, 151 * and a missing API URL does not throw. 152 */ 153 @Test 154 void testGetHost() { 155 assertEquals(THIRD_PARTY_HOST, OAuthParameters.getHost(THIRD_PARTY)); 156 assertEquals(THIRD_PARTY_HOST, OAuthParameters.getHost(THIRD_PARTY_HOST)); 157 assertEquals("localhost", OAuthParameters.getHost("http://localhost:3000/api")); 158 assertNull(OAuthParameters.getHost(null)); 159 assertTrue(OAuthParameters.isUseDefault(null)); 160 OAuthParameters.setUseDefault(null, false); 161 assertTrue(OAuthParameters.isUseDefault(null)); 162 // parameters without a server are not stored under a key without a host 163 new OAuth20Parameters("a-client-id", null, "", "", "", REDIRECT_URI).rememberPreferences(); 164 assertNull(Config.getPref().get("oauth.access-token.parameters.OAuth20.", null)); 165 } 166 167 /** 168 * When the server does not publish its OAuth metadata, the endpoints are those of openstreetmap-website, on the 169 * website rather than below the API URL: {@code <api url>/authorize} is wrong for every OSM API server. 170 */ 171 @Test 172 void testEndpointsWithoutDiscovery() { 173 NetworkManager.setOffline(OnlineResource.ALL); 174 final IOAuthParameters thirdParty = OAuthParameters.createDefault(THIRD_PARTY, OAuthVersion.OAuth20); 175 assertEquals("https://nonprod-mapops.example.org/oauth2/authorize", thirdParty.getAuthorizationUrl()); 176 assertEquals("https://nonprod-mapops.example.org/oauth2/token", thirdParty.getAccessTokenUrl()); 177 assertEquals(THIRD_PARTY, thirdParty.getApiUrl()); 178 // the default API is served from a host of its own 179 final IOAuthParameters osm = OAuthParameters.createDefault("https://api.openstreetmap.org/api", OAuthVersion.OAuth20); 180 assertEquals("https://www.openstreetmap.org/oauth2/authorize", osm.getAuthorizationUrl()); 181 assertEquals("https://www.openstreetmap.org/oauth2/token", osm.getAccessTokenUrl()); 182 } 183 184 /** 185 * The OAuth metadata (RFC 8414) of a server is looked up on its port, such as that of a development server on 186 * http://localhost:3000. Non-regression test: the port was dropped, so the metadata was not found. 187 */ 188 @Test 189 void testDiscoveryUsesThePort() { 190 final WireMockServer server = new WireMockServer(WireMockConfiguration.options().dynamicPort()); 191 server.start(); 192 try { 193 final String website = "http://localhost:" + server.port(); 194 server.stubFor(WireMock.get(WireMock.urlEqualTo("/.well-known/oauth-authorization-server")).willReturn(WireMock.okJson( 195 "{\"authorization_endpoint\": \"" + website + "/discovered/authorize\"," 196 + " \"token_endpoint\": \"" + website + "/discovered/token\"}"))); 197 final IOAuthParameters parameters = OAuthParameters.createDefault(website + "/api", OAuthVersion.OAuth20); 198 assertEquals(website + "/discovered/authorize", parameters.getAuthorizationUrl()); 199 assertEquals(website + "/discovered/token", parameters.getAccessTokenUrl()); 200 } finally { 201 server.stop(); 202 } 62 203 } 63 204 -
trunk/test/unit/org/openstreetmap/josm/gui/ExceptionDialogUtilTest.java
r18853 r19707 2 2 package org.openstreetmap.josm.gui; 3 3 4 import static org.junit.jupiter.api.Assertions.assertEquals; 5 import static org.junit.jupiter.api.Assertions.assertFalse; 6 import static org.junit.jupiter.api.Assertions.assertTrue; 7 8 import java.util.Collections; 9 import java.util.concurrent.atomic.AtomicBoolean; 10 4 11 import org.junit.jupiter.api.Test; 12 import org.openstreetmap.josm.TestUtils; 13 import org.openstreetmap.josm.actions.PreferencesAction; 14 import org.openstreetmap.josm.io.MissingOAuthAccessTokenException; 15 import org.openstreetmap.josm.testutils.annotations.BasicPreferences; 16 import org.openstreetmap.josm.testutils.mockers.HelpAwareOptionPaneMocker; 17 import org.openstreetmap.josm.tools.ExceptionUtil; 5 18 19 import mockit.Mock; 20 import mockit.MockUp; 6 21 import net.trajano.commons.testing.UtilityClassTestUtil; 7 22 … … 9 24 * Unit tests of {@link ExceptionDialogUtil} class. 10 25 */ 26 @BasicPreferences 11 27 class ExceptionDialogUtilTest { 12 28 /** … … 18 34 UtilityClassTestUtil.assertUtilityClassWellDefined(ExceptionDialogUtil.class); 19 35 } 36 37 /** 38 * Without an OAuth Access Token the user is offered to open the preferences, where JOSM is authorized or the 39 * client id or a token is entered. 40 */ 41 @Test 42 void testMissingOAuthAccessTokenOffersThePreferences() { 43 assertEquals(1, explainMissingOAuthAccessToken("Open preferences")); 44 assertEquals(0, explainMissingOAuthAccessToken("Close")); 45 } 46 47 private static int explainMissingOAuthAccessToken(String answer) { 48 TestUtils.assumeWorkingJMockit(); 49 final MissingOAuthAccessTokenException e = MissingOAuthAccessTokenException.clientIdMissing("https://example.org/api"); 50 final HelpAwareOptionPaneMocker mocker = new HelpAwareOptionPaneMocker( 51 Collections.singletonMap(ExceptionUtil.explainMissingOAuthAccessTokenException(e), answer)); 52 final AtomicBoolean opened = new AtomicBoolean(); 53 new MockUp<PreferencesAction>() { 54 @Mock 55 public void run() { 56 opened.set(true); 57 } 58 }; 59 ExceptionDialogUtil.explainMissingOAuthAccessTokenException(e); 60 assertEquals(1, mocker.getInvocationLog().size()); 61 assertEquals("Authentication failed", mocker.getInvocationLog().get(0)[2]); 62 if (opened.get()) { 63 assertTrue(answer.startsWith("Open")); 64 return 1; 65 } 66 assertFalse(answer.startsWith("Open")); 67 return 0; 68 } 20 69 } -
trunk/test/unit/org/openstreetmap/josm/gui/io/DownloadOpenChangesetsTaskTest.java
r18991 r19707 8 8 9 9 import java.awt.GraphicsEnvironment; 10 import java.net.URL;11 10 import java.util.HashMap; 12 11 import java.util.Map; … … 18 17 import org.openstreetmap.josm.TestUtils; 19 18 import org.openstreetmap.josm.data.UserIdentityManager; 20 import org.openstreetmap.josm.gui.oauth.OAuthAuthorizationWizard;21 19 import org.openstreetmap.josm.testutils.annotations.BasicPreferences; 22 20 import org.openstreetmap.josm.testutils.annotations.OsmApi; 23 21 import org.openstreetmap.josm.testutils.mockers.JOptionPaneSimpleMocker; 24 22 import org.openstreetmap.josm.testutils.mockers.WindowMocker; 25 import org.openstreetmap.josm.tools.UserCancelException;26 27 import mockit.Invocation;28 import mockit.Mock;29 import mockit.MockUp;30 23 31 24 /** … … 35 28 @OsmApi(OsmApi.APIType.DEV) 36 29 class DownloadOpenChangesetsTaskTest { 37 /**38 * OAuth wizard mocker.39 */40 public static class OAuthWizardMocker extends MockUp<OAuthAuthorizationWizard> {41 /** {@code true} if wizard has been called */42 public boolean called;43 44 @Mock45 void showDialog() throws UserCancelException {46 this.called = true;47 throw new UserCancelException();48 }49 50 @Mock51 void obtainAccessToken(final Invocation invocation, final URL serverUrl) {52 if (GraphicsEnvironment.isHeadless()) {53 // we can't really let execution proceed any further as construction of the ui54 // elements will fail with a mocked Window55 this.called = true;56 return;57 }58 // else we can allow a bit more of the code to be covered before we raise59 // UserCancelException in showDialog60 invocation.proceed(serverUrl);61 }62 }63 64 30 /** 65 31 * Test of {@link DownloadOpenChangesetsTask} class when anonymous. -
trunk/test/unit/org/openstreetmap/josm/gui/preferences/server/OAuthAuthenticationPreferencesPanelTest.java
r19519 r19707 4 4 import static org.junit.jupiter.api.Assertions.assertAll; 5 5 import static org.junit.jupiter.api.Assertions.assertEquals; 6 import static org.junit.jupiter.api.Assertions.assertFalse; 6 7 import static org.junit.jupiter.api.Assertions.assertNotNull; 7 8 import static org.junit.jupiter.api.Assertions.assertNull; 8 9 import static org.junit.jupiter.api.Assertions.assertSame; 10 import static org.junit.jupiter.api.Assertions.assertTrue; 9 11 import static org.junit.jupiter.api.Assertions.fail; 10 12 import static org.openstreetmap.josm.tools.I18n.tr; 11 13 14 import java.awt.GraphicsEnvironment; 12 15 import java.lang.reflect.Field; 13 16 import java.net.Authenticator; 17 import java.net.URI; 14 18 import java.util.ArrayList; 19 import java.util.Collections; 15 20 import java.util.List; 21 import java.util.concurrent.CountDownLatch; 22 import java.util.concurrent.ExecutionException; 23 import java.util.stream.Stream; 16 24 17 25 import javax.swing.JButton; 26 import javax.swing.JCheckBox; 27 import javax.swing.JOptionPane; 18 28 import javax.swing.JPanel; 29 import javax.swing.JTextField; 19 30 20 31 import org.junit.jupiter.api.AfterEach; 32 import org.junit.jupiter.api.Test; 21 33 import org.junit.jupiter.params.ParameterizedTest; 22 34 import org.junit.jupiter.params.provider.EnumSource; 35 import org.openstreetmap.josm.TestUtils; 23 36 import org.openstreetmap.josm.data.oauth.OAuth20Exception; 24 37 import org.openstreetmap.josm.data.oauth.OAuth20Parameters; 25 38 import org.openstreetmap.josm.data.oauth.OAuth20Token; 26 39 import org.openstreetmap.josm.data.oauth.OAuthAccessTokenHolder; 40 import org.openstreetmap.josm.data.oauth.OAuthParameters; 27 41 import org.openstreetmap.josm.data.oauth.OAuthVersion; 42 import org.openstreetmap.josm.gui.MainApplication; 43 import org.openstreetmap.josm.gui.oauth.AdvancedOAuthPropertiesPanel; 44 import org.openstreetmap.josm.gui.util.GuiHelper; 45 import org.openstreetmap.josm.io.NetworkManager; 46 import org.openstreetmap.josm.io.OnlineResource; 28 47 import org.openstreetmap.josm.io.OsmApi; 29 48 import org.openstreetmap.josm.io.auth.CredentialsAgentException; 30 49 import org.openstreetmap.josm.io.auth.CredentialsManager; 50 import org.openstreetmap.josm.io.remotecontrol.RemoteControl; 51 import org.openstreetmap.josm.spi.preferences.Config; 31 52 import org.openstreetmap.josm.testutils.annotations.BasicPreferences; 53 import org.openstreetmap.josm.testutils.mockers.JOptionPaneSimpleMocker; 54 import org.openstreetmap.josm.testutils.mockers.OpenBrowserMocker; 55 import org.openstreetmap.josm.testutils.mockers.WindowMocker; 56 import org.openstreetmap.josm.tools.HttpClient; 32 57 import org.openstreetmap.josm.tools.ReflectionUtils; 33 58 … … 56 81 57 82 assertAll(exceptionList.stream().map(e -> () -> fail(e))); 83 // removing a token keeps the OAuth settings of the server 84 Config.getPref().removeSensitive("oauth.access-token.parameters.OAuth20." + OsmApi.getOsmApi().getHost()); 85 Config.getPref().put("oauth.settings.use-default." + OsmApi.getOsmApi().getHost(), null); 86 NetworkManager.setOnline(OnlineResource.ALL); 58 87 } 59 88 … … 74 103 assertSame(pnlAlreadyAuthorised.get(panel), holder.getComponent(0), "Authentication should now be set"); 75 104 assertNotNull(getAuthorization(oAuthVersion)); 76 final JPanel buttons = (JPanel) ((JPanel) pnlAlreadyAuthorised.get(panel)).getComponent(5); 77 final JButton action = (JButton) buttons.getComponent(2); 105 final JButton action = (JButton) getAlreadyAuthorisedButtons(panel).getComponent(2); 78 106 assertEquals(tr("Remove token"), action.getText(), "The selected button should be for removing the token"); 79 107 action.getAction().actionPerformed(null); 80 108 panel.saveToPreferences(); // Save to preferences should make the removal permanent 81 // Ensure that the token holder has been reset for OAuth 1.0a109 // Ensure that the token holder has been reset 82 110 OAuthAccessTokenHolder.getInstance().clear(); 83 111 OAuthAccessTokenHolder.getInstance().init(CredentialsManager.getInstance()); … … 85 113 panel.initFromPreferences(); 86 114 assertSame(pnlNotYetAuthorised.get(panel), holder.getComponent(0), "No authentication should be set"); 115 } 116 117 /** 118 * The "New Access Token" button follows the client id entered in the advanced OAuth parameters, like the 119 * "Authorize now" button does. Non-regression test: the buttons of the panel shown when a token exists were 120 * looked up by component index, which pointed at the filler panel instead, so this button was never updated. 121 * @throws ReflectiveOperationException if a field cannot be accessed 122 * @throws CredentialsAgentException if the token cannot be stored 123 * @throws OAuth20Exception if the token cannot be built 124 * @throws ExecutionException if waiting for the worker fails 125 * @throws InterruptedException if waiting for the worker is interrupted 126 */ 127 @Test 128 void testRenewButtonFollowsTheClientId() throws ReflectiveOperationException, CredentialsAgentException, OAuth20Exception, 129 ExecutionException, InterruptedException { 130 // the default parameters of the API would otherwise be looked up with an RFC 8414 request 131 NetworkManager.setOffline(OnlineResource.ALL); 132 try { 133 final OAuthAuthenticationPreferencesPanel panel = new OAuthAuthenticationPreferencesPanel(OAuthVersion.OAuth20); 134 addAuthorization(OAuthVersion.OAuth20); 135 panel.initFromPreferences(); 136 waitForWorkerAndEdt(); 137 138 final Field pnlAdvancedProperties = OAuthAuthenticationPreferencesPanel.class.getDeclaredField("pnlAdvancedProperties"); 139 final Field cbUseDefaults = AdvancedOAuthPropertiesPanel.class.getDeclaredField("cbUseDefaults"); 140 final Field tfClientId = AdvancedOAuthPropertiesPanel.class.getDeclaredField("tfClientId"); 141 ReflectionUtils.setObjectsAccessible(pnlAdvancedProperties, cbUseDefaults, tfClientId); 142 final AdvancedOAuthPropertiesPanel advanced = (AdvancedOAuthPropertiesPanel) pnlAdvancedProperties.get(panel); 143 ((JCheckBox) cbUseDefaults.get(advanced)).setSelected(false); 144 final JTextField clientId = (JTextField) tfClientId.get(advanced); 145 final JButton renew = (JButton) getAlreadyAuthorisedButtons(panel).getComponent(0); 146 assertEquals(tr("New Access Token"), renew.getText()); 147 148 clientId.setText(""); 149 assertFalse(renew.isEnabled(), "without a client id there is nothing to authorize with"); 150 clientId.setText("a-client-id"); 151 assertTrue(renew.isEnabled()); 152 } finally { 153 NetworkManager.setOnline(OnlineResource.ALL); 154 Config.getPref().put("oauth.settings.use-default", null); 155 } 156 } 157 158 /** 159 * Removing the token keeps the OAuth settings entered for the server, so that a new token can be obtained 160 * without entering them again. 161 * @throws ReflectiveOperationException if a field cannot be accessed 162 * @throws CredentialsAgentException if the token cannot be stored 163 * @throws OAuth20Exception if the token cannot be built 164 * @throws ExecutionException if waiting for the worker fails 165 * @throws InterruptedException if waiting for the worker is interrupted 166 */ 167 @Test 168 void testRemoveTokenKeepsTheEnteredSettings() throws ReflectiveOperationException, CredentialsAgentException, OAuth20Exception, 169 ExecutionException, InterruptedException { 170 // the default parameters of the API would otherwise be looked up with an RFC 8414 request 171 NetworkManager.setOffline(OnlineResource.ALL); 172 // the user entered the settings, and obtained a token with them 173 OAuthParameters.setUseDefault(OsmApi.getOsmApi().getServerUrl(), false); 174 addAuthorization(OAuthVersion.OAuth20); 175 final OAuthAuthenticationPreferencesPanel panel = new OAuthAuthenticationPreferencesPanel(OAuthVersion.OAuth20); 176 panel.initFromPreferences(); 177 waitForWorkerAndEdt(); 178 ((JButton) getAlreadyAuthorisedButtons(panel).getComponent(2)).getAction().actionPerformed(null); 179 panel.saveToPreferences(); 180 assertNull(getAuthorization(OAuthVersion.OAuth20)); 181 182 final OAuthAuthenticationPreferencesPanel reopened = new OAuthAuthenticationPreferencesPanel(OAuthVersion.OAuth20); 183 reopened.initFromPreferences(); 184 waitForWorkerAndEdt(); 185 final AdvancedOAuthPropertiesPanel advanced = getAdvancedProperties(reopened); 186 assertFalse(advanced.isUseDefaultSettings()); 187 assertEquals("fake_id", advanced.getEnteredClientId()); 188 } 189 190 /** 191 * The "Authorize now" button is enabled according to the latest change of the advanced OAuth parameters. 192 * <p> 193 * Non-regression test: with "use default settings" ticked, the client id is looked up on the worker thread, and 194 * the result of that lookup was applied even when the parameters had changed again in the meantime, for example 195 * because the box was unticked and no client id entered. 196 * @throws ReflectiveOperationException if a field cannot be accessed 197 * @throws ExecutionException if waiting for the worker fails 198 * @throws InterruptedException if waiting for the worker is interrupted 199 */ 200 @Test 201 void testAuthorizeButtonFollowsTheLatestChange() throws ReflectiveOperationException, ExecutionException, InterruptedException { 202 NetworkManager.setOffline(OnlineResource.ALL); 203 final OAuthAuthenticationPreferencesPanel panel = new OAuthAuthenticationPreferencesPanel(OAuthVersion.OAuth20); 204 panel.initFromPreferences(); 205 waitForWorkerAndEdt(); 206 final AdvancedOAuthPropertiesPanel advanced = getAdvancedProperties(panel); 207 assertTrue(advanced.isUseDefaultSettings()); 208 final Field pnlNotYetAuthorised = OAuthAuthenticationPreferencesPanel.class.getDeclaredField("pnlNotYetAuthorised"); 209 ReflectionUtils.setObjectsAccessible(pnlNotYetAuthorised); 210 final JButton authorize = (JButton) ((JPanel) pnlNotYetAuthorised.get(panel)).getComponent(1); 211 assertTrue(authorize.isEnabled(), "JOSM has a client id for the default API"); 212 213 // hold the worker, so that the lookup made with the default settings finishes after the next change 214 final CountDownLatch latch = new CountDownLatch(1); 215 MainApplication.worker.execute(() -> { 216 try { 217 latch.await(); 218 } catch (InterruptedException e) { 219 Thread.currentThread().interrupt(); 220 } 221 }); 222 try { 223 ((JTextField) getAdvancedField(advanced, "tfClientId")).setText(""); 224 ((JCheckBox) getAdvancedField(advanced, "cbUseDefaults")).setSelected(false); 225 assertFalse(authorize.isEnabled(), "without a client id there is nothing to authorize with"); 226 } finally { 227 latch.countDown(); 228 } 229 waitForWorkerAndEdt(); 230 assertFalse(authorize.isEnabled(), "the lookup made with the default settings overrode a later change"); 231 } 232 233 /** 234 * A pasted access token works with nothing else: here for a server JOSM has no client id for, with no client id 235 * entered and no network. It is taken over when the preferences are saved, not before, so that cancelling them 236 * leaves the token as it was. 237 * @throws Exception if a field cannot be accessed, waiting for the worker fails or the request cannot be signed 238 */ 239 @Test 240 void testPastedTokenWorksWithNothingElse() throws Exception { 241 NetworkManager.setOffline(OnlineResource.ALL); 242 final String apiUrl = "https://nonprod-mapops.example.org/api"; 243 Config.getPref().put("osm-server.url", apiUrl); 244 try { 245 final OAuthAuthenticationPreferencesPanel panel = new OAuthAuthenticationPreferencesPanel(OAuthVersion.OAuth20); 246 panel.initFromPreferences(); 247 waitForWorkerAndEdt(); 248 final AdvancedOAuthPropertiesPanel advanced = getAdvancedProperties(panel); 249 assertEquals("", advanced.getEnteredClientId()); 250 251 final JTextField tfAccessToken = (JTextField) getAdvancedField(advanced, "tfAccessToken"); 252 assertTrue(advanced.isUseDefaultSettings()); 253 assertTrue(tfAccessToken.isEnabled(), "a token can be pasted while the default settings are used"); 254 tfAccessToken.setText(" a-pasted-token\n"); 255 tfAccessToken.postActionEvent(); 256 assertNull(OAuthAccessTokenHolder.getInstance().getAccessToken(apiUrl, OAuthVersion.OAuth20), 257 "taken over before the preferences were saved, so cancelling them would not undo it"); 258 panel.saveToPreferences(); 259 260 final OAuth20Token token = (OAuth20Token) getAuthorization(OAuthVersion.OAuth20); 261 assertNotNull(token, "the token was not saved"); 262 assertEquals("a-pasted-token", token.getBearerToken()); 263 final HttpClient request = HttpClient.create(URI.create(apiUrl + "/0.6/changeset/create").toURL(), "PUT"); 264 token.sign(request); 265 assertEquals("Bearer a-pasted-token", request.getRequestHeader("Authorization")); 266 } finally { 267 CredentialsManager.getInstance().storeOAuthAccessToken(OsmApi.getOsmApi().getHost(), null); 268 Config.getPref().removeSensitive("oauth.access-token.parameters.OAuth20." + OsmApi.getOsmApi().getHost()); 269 Config.getPref().put("osm-server.url", null); 270 } 271 } 272 273 /** 274 * A token which the user did not change is kept as it is, rather than replaced by a token built from its text: 275 * that would lose everything else the token holds, such as its parameters. 276 * @throws CredentialsAgentException if the token cannot be stored 277 * @throws OAuth20Exception if the token cannot be built 278 * @throws ExecutionException if waiting for the worker fails 279 * @throws InterruptedException if waiting for the worker is interrupted 280 * @throws ReflectiveOperationException if a field cannot be accessed 281 */ 282 @Test 283 void testUnchangedTokenIsKept() throws CredentialsAgentException, OAuth20Exception, ExecutionException, InterruptedException, 284 ReflectiveOperationException { 285 NetworkManager.setOffline(OnlineResource.ALL); 286 addAuthorization(OAuthVersion.OAuth20); 287 final OAuthAuthenticationPreferencesPanel panel = new OAuthAuthenticationPreferencesPanel(OAuthVersion.OAuth20); 288 panel.initFromPreferences(); 289 waitForWorkerAndEdt(); 290 assertEquals("fake_token", getAdvancedProperties(panel).getAccessToken()); 291 panel.saveToPreferences(); 292 293 final OAuth20Token token = (OAuth20Token) getAuthorization(OAuthVersion.OAuth20); 294 assertEquals("fake_token", token.getBearerToken()); 295 assertEquals("fake_id", token.getParameters().getClientId()); 296 } 297 298 /** 299 * Clearing the access token removes it, like the "Remove token" button does. 300 * @throws CredentialsAgentException if the token cannot be stored 301 * @throws OAuth20Exception if the token cannot be built 302 * @throws ExecutionException if waiting for the worker fails 303 * @throws InterruptedException if waiting for the worker is interrupted 304 * @throws ReflectiveOperationException if a field cannot be accessed 305 */ 306 @Test 307 void testClearedTokenIsRemoved() throws CredentialsAgentException, OAuth20Exception, ExecutionException, InterruptedException, 308 ReflectiveOperationException { 309 NetworkManager.setOffline(OnlineResource.ALL); 310 addAuthorization(OAuthVersion.OAuth20); 311 final OAuthAuthenticationPreferencesPanel panel = new OAuthAuthenticationPreferencesPanel(OAuthVersion.OAuth20); 312 panel.initFromPreferences(); 313 waitForWorkerAndEdt(); 314 getAdvancedProperties(panel).setAccessToken(""); 315 assertNotNull(OAuthAccessTokenHolder.getInstance().getAccessToken(OsmApi.getOsmApi().getServerUrl(), OAuthVersion.OAuth20), 316 "removed before the preferences were saved, so cancelling them would not undo it"); 317 panel.saveToPreferences(); 318 assertNull(getAuthorization(OAuthVersion.OAuth20)); 319 } 320 321 /** 322 * "Test Access Token" tests the token in the field: with the field cleared there is none to test, rather than 323 * the stored token, which the user is about to remove. 324 * @throws Exception if a field cannot be accessed, the token cannot be stored or waiting for the worker fails 325 */ 326 @Test 327 void testNothingToTestWhenTheTokenIsCleared() throws Exception { 328 TestUtils.assumeWorkingJMockit(); 329 if (GraphicsEnvironment.isHeadless()) { 330 new WindowMocker(); 331 } 332 final JOptionPaneSimpleMocker mocker = new JOptionPaneSimpleMocker(Collections.singletonMap( 333 "There is no Access Token to test.", JOptionPane.OK_OPTION)); 334 NetworkManager.setOffline(OnlineResource.ALL); 335 addAuthorization(OAuthVersion.OAuth20); 336 final OAuthAuthenticationPreferencesPanel panel = new OAuthAuthenticationPreferencesPanel(OAuthVersion.OAuth20); 337 panel.initFromPreferences(); 338 waitForWorkerAndEdt(); 339 getAdvancedProperties(panel).setAccessToken(""); 340 final JButton test = (JButton) getAlreadyAuthorisedButtons(panel).getComponent(1); 341 assertEquals(tr("Test Access Token"), test.getText()); 342 343 test.doClick(); 344 assertEquals(1, mocker.getInvocationLog().size(), "the stored token was tested instead"); 345 } 346 347 /** 348 * "Authorize now" authorizes JOSM in the web browser straight away, with the OAuth parameters shown in the panel. 349 * @throws Exception if a field cannot be accessed or waiting for the worker fails 350 */ 351 @Test 352 void testAuthorizeNowUsesTheDisplayedParameters() throws Exception { 353 TestUtils.assumeWorkingJMockit(); 354 new OpenBrowserMocker(); 355 OpenBrowserMocker.getCalledURIs().clear(); 356 NetworkManager.setOffline(OnlineResource.ALL); 357 RemoteControl.stop(); 358 try { 359 final OAuthAuthenticationPreferencesPanel panel = new OAuthAuthenticationPreferencesPanel(OAuthVersion.OAuth20); 360 panel.initFromPreferences(); 361 waitForWorkerAndEdt(); 362 final AdvancedOAuthPropertiesPanel advanced = getAdvancedProperties(panel); 363 advanced.setAdvancedParameters(new OAuth20Parameters("an-entered-client-id", null, "https://example.org/oauth2/token", 364 "https://example.org/oauth2/authorize", OsmApi.getOsmApi().getServerUrl(), "http://127.0.0.1:8111/oauth_authorization")); 365 assertFalse(advanced.isUseDefaultSettings()); 366 final Field pnlNotYetAuthorised = OAuthAuthenticationPreferencesPanel.class.getDeclaredField("pnlNotYetAuthorised"); 367 ReflectionUtils.setObjectsAccessible(pnlNotYetAuthorised); 368 final JButton authorize = (JButton) ((JPanel) pnlNotYetAuthorised.get(panel)).getComponent(1); 369 assertEquals(tr("Authorize now"), authorize.getText()); 370 371 authorize.doClick(); 372 GuiHelper.runInEDTAndWait(() -> { }); 373 374 assertEquals(1, OpenBrowserMocker.getCalledURIs().size()); 375 final String url = OpenBrowserMocker.getCalledURIs().get(0).toString(); 376 assertTrue(url.startsWith("https://example.org/oauth2/authorize?"), url); 377 assertTrue(url.contains("client_id=an-entered-client-id"), url); 378 } finally { 379 RemoteControl.stop(); 380 } 381 } 382 383 /** 384 * A failed attempt at a new Access Token leaves the token JOSM has as it is. 385 * <p> 386 * Non-regression test: the token was replaced by none whenever the authorization failed, for example when the 387 * server refused to exchange the code for a token, so a failed renewal lost a working token. 388 * @throws Exception if a field cannot be accessed, the token cannot be stored or the redirect cannot be sent 389 */ 390 @Test 391 void testFailedRenewalKeepsTheToken() throws Exception { 392 TestUtils.assumeWorkingJMockit(); 393 new OpenBrowserMocker(); 394 OpenBrowserMocker.getCalledURIs().clear(); 395 new JOptionPaneSimpleMocker(Collections.singletonMap( 396 "Authentication failed, please check browser for details.", JOptionPane.OK_OPTION)); 397 NetworkManager.setOffline(OnlineResource.ALL); 398 RemoteControl.stop(); 399 addAuthorization(OAuthVersion.OAuth20); 400 try { 401 final OAuthAuthenticationPreferencesPanel panel = new OAuthAuthenticationPreferencesPanel(OAuthVersion.OAuth20); 402 panel.initFromPreferences(); 403 waitForWorkerAndEdt(); 404 // the token request goes to a port nothing listens on, so that the exchange fails 405 getAdvancedProperties(panel).setAdvancedParameters(new OAuth20Parameters("an-entered-client-id", null, 406 "http://127.0.0.1:1/oauth2/token", "https://example.org/oauth2/authorize", 407 OsmApi.getOsmApi().getServerUrl(), "http://127.0.0.1:8111/oauth_authorization")); 408 final JButton renew = (JButton) getAlreadyAuthorisedButtons(panel).getComponent(0); 409 assertEquals(tr("New Access Token"), renew.getText()); 410 411 renew.doClick(); 412 GuiHelper.runInEDTAndWait(() -> { }); 413 assertEquals(1, OpenBrowserMocker.getCalledURIs().size()); 414 final String state = Stream.of(OpenBrowserMocker.getCalledURIs().get(0).getQuery().split("&")) 415 .filter(p -> p.startsWith("state=")).map(p -> p.substring("state=".length())).findFirst().orElseThrow(); 416 // the web browser is redirected to JOSM with a code 417 final HttpClient redirect = HttpClient.create( 418 URI.create("http://127.0.0.1:8111/oauth_authorization?code=a-code&state=" + state).toURL()); 419 try { 420 redirect.connect(); 421 } finally { 422 redirect.disconnect(); 423 } 424 GuiHelper.runInEDTAndWait(() -> { }); 425 426 final OAuth20Token token = (OAuth20Token) getAuthorization(OAuthVersion.OAuth20); 427 assertNotNull(token, "the token was lost"); 428 assertEquals("fake_token", token.getBearerToken()); 429 } finally { 430 RemoteControl.stop(); 431 } 432 } 433 434 private static AdvancedOAuthPropertiesPanel getAdvancedProperties(OAuthAuthenticationPreferencesPanel panel) 435 throws ReflectiveOperationException { 436 final Field pnlAdvancedProperties = OAuthAuthenticationPreferencesPanel.class.getDeclaredField("pnlAdvancedProperties"); 437 ReflectionUtils.setObjectsAccessible(pnlAdvancedProperties); 438 return (AdvancedOAuthPropertiesPanel) pnlAdvancedProperties.get(panel); 439 } 440 441 private static Object getAdvancedField(AdvancedOAuthPropertiesPanel advanced, String name) throws ReflectiveOperationException { 442 final Field field = AdvancedOAuthPropertiesPanel.class.getDeclaredField(name); 443 ReflectionUtils.setObjectsAccessible(field); 444 return field.get(advanced); 445 } 446 447 /** 448 * Waits until the panel has settled. The advanced parameters fill themselves in from the worker, then the EDT, 449 * and setting them re-evaluates the "Authorize now" buttons, which queues more work on the worker that again 450 * finishes on the EDT; so this goes round twice. 451 * @throws ExecutionException if waiting for the worker fails 452 * @throws InterruptedException if waiting for the worker is interrupted 453 */ 454 private static void waitForWorkerAndEdt() throws ExecutionException, InterruptedException { 455 for (int i = 0; i < 2; i++) { 456 MainApplication.worker.submit(() -> { }).get(); 457 GuiHelper.runInEDTAndWait(() -> { }); 458 } 459 } 460 461 private static JPanel getAlreadyAuthorisedButtons(OAuthAuthenticationPreferencesPanel panel) throws ReflectiveOperationException { 462 final Field pnlAlreadyAuthorised = OAuthAuthenticationPreferencesPanel.class.getDeclaredField("pnlAlreadyAuthorised"); 463 ReflectionUtils.setObjectsAccessible(pnlAlreadyAuthorised); 464 final Object alreadyAuthorised = pnlAlreadyAuthorised.get(panel); 465 final Field pnlButtons = alreadyAuthorised.getClass().getDeclaredField("pnlButtons"); 466 ReflectionUtils.setObjectsAccessible(pnlButtons); 467 return (JPanel) pnlButtons.get(alreadyAuthorised); 87 468 } 88 469 -
trunk/test/unit/org/openstreetmap/josm/io/OsmConnectionTest.java
r19654 r19707 3 3 4 4 import static org.junit.jupiter.api.Assertions.assertEquals; 5 import static org.junit.jupiter.api.Assertions.assertFalse; 5 6 import static org.junit.jupiter.api.Assertions.assertNotNull; 6 7 import static org.junit.jupiter.api.Assertions.assertNull; … … 8 9 import static org.junit.jupiter.api.Assertions.assertTrue; 9 10 11 import java.awt.GraphicsEnvironment; 10 12 import java.net.MalformedURLException; 11 13 import java.net.URI; 14 import java.util.Collections; 12 15 13 16 import javax.swing.JOptionPane; … … 16 19 import org.junit.jupiter.api.BeforeEach; 17 20 import org.junit.jupiter.api.Test; 21 import org.openstreetmap.josm.TestUtils; 18 22 import org.openstreetmap.josm.data.oauth.IOAuthParameters; 19 23 import org.openstreetmap.josm.data.oauth.OAuth20Exception; … … 21 25 import org.openstreetmap.josm.data.oauth.OAuth20Token; 22 26 import org.openstreetmap.josm.data.oauth.OAuthAccessTokenHolder; 27 import org.openstreetmap.josm.data.oauth.OAuthParameters; 23 28 import org.openstreetmap.josm.data.oauth.OAuthVersion; 24 29 import org.openstreetmap.josm.spi.preferences.Config; 25 30 import org.openstreetmap.josm.testutils.annotations.BasicPreferences; 31 import org.openstreetmap.josm.testutils.mockers.JOptionPaneSimpleMocker; 32 import org.openstreetmap.josm.testutils.mockers.WindowMocker; 26 33 import org.openstreetmap.josm.tools.HttpClient; 27 34 … … 55 62 OAuthAccessTokenHolder.getInstance().clear(); 56 63 // preferences and the token holder are static state shared with the other tests of this class 57 Config.getPref().put("oauth.access-token.parameters." + OAuthVersion.OAuth20 + "." + API_URL, null); 64 Config.getPref().put("oauth.access-token.parameters." + OAuthVersion.OAuth20 + "." + URI.create(API_URL).getHost(), null); 65 Config.getPref().put("oauth.settings.use-default." + URI.create(API_URL).getHost(), null); 58 66 Config.getPref().put("osm-server.url", null); 59 67 } … … 64 72 65 73 /** 66 * Stores the advanced OAuth parameters the way the authentication preferences do , that is under the API URL.74 * Stores the advanced OAuth parameters the way the authentication preferences do. 67 75 */ 68 76 private static OAuth20Parameters rememberParameters() { 69 77 final OAuth20Parameters parameters = new OAuth20Parameters(CLIENT_ID, null, API_URL, API_URL, REDIRECT_URI); 78 OAuthParameters.setUseDefault(API_URL, false); 70 79 parameters.rememberPreferences(); 71 80 return parameters; … … 115 124 () -> new TestConnection().addOAuth20AuthorizationHeader(client)); 116 125 assertNotNull(thrown.getMessage(), "gave up only after asking the user, rather than for the missing client id"); 126 assertTrue(thrown.isClientIdMissing(), "the user is not told what is missing"); 117 127 assertTrue(thrown.getMessage().contains(API_URL), thrown.getMessage()); 118 128 assertNull(client.getRequestHeader("Authorization")); 129 } 130 131 /** 132 * A token is obtained for the API, so for a request to another host JOSM does not ask the user to authorize it, 133 * which would not give a token for that request anyway. 134 * @throws MalformedURLException never 135 */ 136 @Test 137 void testNoAuthorizationForAnotherHost() throws MalformedURLException { 138 TestUtils.assumeWorkingJMockit(); 139 if (GraphicsEnvironment.isHeadless()) { 140 new WindowMocker(); 141 } 142 final JOptionPaneSimpleMocker mocker = new JOptionPaneSimpleMocker( 143 Collections.singletonMap("Obtain OAuth 2.0 token for authentication?", JOptionPane.NO_OPTION)); 144 rememberParameters(); 145 146 final HttpClient client = HttpClient.create(URI.create("https://elsewhere.example.org/api/0.6/user/details").toURL()); 147 final MissingOAuthAccessTokenException thrown = assertThrows(MissingOAuthAccessTokenException.class, 148 () -> new TestConnection().addOAuth20AuthorizationHeader(client)); 149 assertFalse(thrown.isClientIdMissing()); 150 assertEquals(0, mocker.getInvocationLog().size(), "asked to obtain a token for another host"); 151 } 152 153 /** 154 * A token pasted by the user signs the connection with nothing else: no client id, no endpoints, no network. 155 * @throws Exception if the connection cannot be signed 156 */ 157 @Test 158 void testPastedTokenSignsTheConnection() throws Exception { 159 OAuthAccessTokenHolder.getInstance().setAccessToken(API_URL, 160 OAuth20Token.fromAccessToken(new OAuth20Parameters("", null, "", "", API_URL, ""), "a-pasted-token")); 161 162 final HttpClient client = apiRequest(); 163 new TestConnection().addOAuth20AuthorizationHeader(client); 164 assertEquals("Bearer a-pasted-token", client.getRequestHeader("Authorization")); 119 165 } 120 166 -
trunk/test/unit/org/openstreetmap/josm/io/auth/JosmPreferencesCredentialAgentTest.java
r19652 r19707 2 2 package org.openstreetmap.josm.io.auth; 3 3 4 import static org.junit.jupiter.api.Assertions.assertEquals; 4 5 import static org.junit.jupiter.api.Assertions.assertFalse; 5 6 import static org.junit.jupiter.api.Assertions.assertNotNull; … … 26 27 27 28 /** 28 * Removing an OAuth token removes it from the preferences, not only the parameters stored with it. 29 * Removing an OAuth token removes it from the preferences, and keeps the parameters stored with it: they are the 30 * OAuth settings of the server too, which are needed to obtain the next token. 29 31 * <p> 30 * Non-regression test: both keys were built with the {@code parameters} prefix, so the token itself stayed in the31 * preferences in clear text. {@link CredentialsAgentTest#testLookupAndStoreOAuthTokens} did not notice, because a32 * lookup needs both keys and so already fail sonce the parametersare gone.32 * Non-regression test for #24932: both keys were built with the {@code parameters} prefix, so the token itself 33 * stayed in the preferences in clear text. {@link CredentialsAgentTest#testLookupAndStoreOAuthTokens} did not 34 * notice, because a lookup needs both keys and so already failed once the parameters were gone. 33 35 * @throws CredentialsAgentException if the token cannot be stored or removed 34 36 * @throws OAuth20Exception if the token cannot be built … … 45 47 "{\"access_token\": \"a-secret-token\", \"token_type\": \"bearer\"}")); 46 48 assertNotNull(Config.getPref().get(tokenKey, null)); 47 assertNotNull(Config.getPref().get(parametersKey, null)); 49 final String parameters = Config.getPref().get(parametersKey, null); 50 assertNotNull(parameters); 48 51 49 52 agent.storeOAuthAccessToken(host, null); 50 53 51 54 assertNull(Config.getPref().get(tokenKey, null), "the token is still stored in the preferences"); 52 assertNull(Config.getPref().get(parametersKey, null));53 55 assertFalse(Config.getPref().getSensitive().contains(tokenKey)); 54 assertFalse(Config.getPref().getSensitive().contains(parametersKey)); 56 assertNull(agent.lookupOAuthAccessToken(host)); 57 assertEquals(parameters, Config.getPref().get(parametersKey, null), "the OAuth settings of the server are gone"); 58 Config.getPref().removeSensitive(parametersKey); 55 59 } 56 60 } -
trunk/test/unit/org/openstreetmap/josm/testutils/JOSMTestRules.java
r19519 r19707 51 51 import org.openstreetmap.josm.data.projection.Projections; 52 52 import org.openstreetmap.josm.gui.MainApplication; 53 import org.openstreetmap.josm.gui.oauth.OAuthAuthorizationWizard;54 53 import org.openstreetmap.josm.gui.preferences.imagery.ImageryPreferenceTestIT; 55 54 import org.openstreetmap.josm.gui.util.GuiHelper; 56 55 import org.openstreetmap.josm.io.OsmApi; 57 56 import org.openstreetmap.josm.io.OsmApiInitializationException; 58 import org.openstreetmap.josm.io.OsmConnection;59 57 import org.openstreetmap.josm.io.OsmTransferCanceledException; 60 58 import org.openstreetmap.josm.spi.preferences.Config; … … 550 548 // Setup callbacks 551 549 DeleteCommand.setDeletionCallback(DeleteAction.defaultDeletionCallback); 552 OsmConnection.setOAuthAccessTokenFetcher(OAuthAuthorizationWizard::obtainAccessToken);553 550 HttpClient.setFactory(Http1Client::new); 554 551 -
trunk/test/unit/org/openstreetmap/josm/testutils/annotations/JosmDefaults.java
r19519 r19707 21 21 import org.openstreetmap.josm.data.UserIdentityManager; 22 22 import org.openstreetmap.josm.data.osm.User; 23 import org.openstreetmap.josm.gui.oauth.OAuthAuthorizationWizard;24 23 import org.openstreetmap.josm.gui.util.GuiHelper; 25 import org.openstreetmap.josm.io.OsmConnection;26 24 import org.openstreetmap.josm.testutils.JOSMTestRules; 27 25 import org.openstreetmap.josm.tools.Logging; … … 60 58 // Setup callbacks 61 59 DeleteCommand.setDeletionCallback(DeleteAction.defaultDeletionCallback); 62 OsmConnection.setOAuthAccessTokenFetcher(OAuthAuthorizationWizard::obtainAccessToken);63 60 } 64 61 -
trunk/test/unit/org/openstreetmap/josm/tools/ExceptionUtilTest.java
r19227 r19707 3 3 4 4 import static org.junit.jupiter.api.Assertions.assertEquals; 5 import static org.junit.jupiter.api.Assertions.assertTrue; 5 6 6 7 import java.io.IOException; … … 279 280 280 281 /** 282 * Without a client id, JOSM cannot obtain a token, and says so rather than to generate one. 283 */ 284 @Test 285 void testExplainMissingOAuthClientId() { 286 // the server JOSM gave up on, whichever is configured by the time this is explained 287 final String explanation = ExceptionUtil.explainMissingOAuthAccessTokenException( 288 MissingOAuthAccessTokenException.clientIdMissing("https://other.example.org/api")); 289 assertTrue(explanation.contains("'https://other.example.org/api'"), explanation); 290 assertTrue(explanation.contains("because it has no OAuth Client ID for it"), explanation); 291 } 292 293 /** 281 294 * Test of {@link ExceptionUtil#explainNestedIllegalDataException} method. 282 295 */
Note:
See TracChangeset
for help on using the changeset viewer.
