Changeset 19707 in josm for trunk/test


Ignore:
Timestamp:
2026-11-26T22:24:37+01:00 (4 days ago)
Author:
stoecker
Message:

see #24928 - patch by wangi - Cleanup OAuth

Location:
trunk/test/unit/org/openstreetmap/josm
Files:
2 added
4 deleted
11 edited

Legend:

Unmodified
Added
Removed
  • trunk/test/unit/org/openstreetmap/josm/data/PreferencesTest.java

    r18870 r19707  
    33
    44import static org.junit.jupiter.api.Assertions.assertEquals;
     5import static org.junit.jupiter.api.Assertions.assertNull;
     6
     7import java.io.File;
     8import java.io.IOException;
     9import java.nio.charset.StandardCharsets;
     10import java.nio.file.Files;
     11import java.nio.file.Path;
     12
     13import javax.xml.stream.XMLStreamException;
    514
    615import org.junit.jupiter.api.Test;
     16import org.junit.jupiter.api.io.TempDir;
     17import org.openstreetmap.josm.spi.preferences.IBaseDirectories;
    718import org.openstreetmap.josm.testutils.annotations.BasicPreferences;
    819import org.openstreetmap.josm.testutils.annotations.OsmApi;
     20import org.xml.sax.SAXException;
    921
    1022/**
    … …  
    2638                Preferences.main().toXML(true));
    2739    }
     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    }
    2881}
  • trunk/test/unit/org/openstreetmap/josm/data/UserIdentityManagerTest.java

    r18037 r19707  
    1414import java.util.stream.Stream;
    1515
     16import org.openstreetmap.josm.data.oauth.OAuth20Parameters;
     17import org.openstreetmap.josm.data.oauth.OAuth20Token;
     18import org.openstreetmap.josm.data.oauth.OAuthAccessTokenHolder;
    1619import org.openstreetmap.josm.data.osm.User;
    1720import org.openstreetmap.josm.data.osm.UserInfo;
     21import org.openstreetmap.josm.io.NetworkManager;
     22import org.openstreetmap.josm.io.OnlineResource;
     23import org.openstreetmap.josm.io.OsmApi;
     24import org.openstreetmap.josm.io.auth.CredentialsManager;
    1825import org.openstreetmap.josm.spi.preferences.Config;
    1926import org.openstreetmap.josm.testutils.annotations.BasicPreferences;
    … …  
    3946        userInfo.setDescription(description);
    4047        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        }
    4182    }
    4283
  • trunk/test/unit/org/openstreetmap/josm/data/oauth/OAuthParametersTest.java

    r19638 r19707  
    33
    44import static org.junit.jupiter.api.Assertions.assertEquals;
     5import static org.junit.jupiter.api.Assertions.assertFalse;
    56import static org.junit.jupiter.api.Assertions.assertNotEquals;
    67import static org.junit.jupiter.api.Assertions.assertNotNull;
     8import static org.junit.jupiter.api.Assertions.assertNull;
     9import static org.junit.jupiter.api.Assertions.assertTrue;
    710
    811import org.junit.jupiter.api.AfterEach;
    … …  
    1518import org.openstreetmap.josm.tools.Logging;
    1619
     20import com.github.tomakehurst.wiremock.WireMockServer;
     21import com.github.tomakehurst.wiremock.client.WireMock;
     22import com.github.tomakehurst.wiremock.core.WireMockConfiguration;
     23
    1724import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
    1825import nl.jqno.equalsverifier.EqualsVerifier;
    … …  
    2431class OAuthParametersTest {
    2532
     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
    2638    @AfterEach
    2739    void tearDown() {
    2840        NetworkManager.setOnline(OnlineResource.ALL);
    29         // the API URL is static state shared with the other tests of this class
     41        // the preferences are static state shared with the other tests of this class
    3042        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();
    3156    }
    3257
    … …  
    5277        assertEquals("", OAuthParameters.createFromApiUrl(thirdParty, OAuthVersion.OAuth20).getClientId());
    5378
    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);
    5682        new OAuth20Parameters("entered-client-id", null, thirdParty, thirdParty, "http://127.0.0.1:8111/oauth_authorization")
    5783                .rememberPreferences();
    … …  
    6086        assertEquals("https://api.openhistoricalmap.org/api",
    6187                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        }
    62203    }
    63204
  • trunk/test/unit/org/openstreetmap/josm/gui/ExceptionDialogUtilTest.java

    r18853 r19707  
    22package org.openstreetmap.josm.gui;
    33
     4import static org.junit.jupiter.api.Assertions.assertEquals;
     5import static org.junit.jupiter.api.Assertions.assertFalse;
     6import static org.junit.jupiter.api.Assertions.assertTrue;
     7
     8import java.util.Collections;
     9import java.util.concurrent.atomic.AtomicBoolean;
     10
    411import org.junit.jupiter.api.Test;
     12import org.openstreetmap.josm.TestUtils;
     13import org.openstreetmap.josm.actions.PreferencesAction;
     14import org.openstreetmap.josm.io.MissingOAuthAccessTokenException;
     15import org.openstreetmap.josm.testutils.annotations.BasicPreferences;
     16import org.openstreetmap.josm.testutils.mockers.HelpAwareOptionPaneMocker;
     17import org.openstreetmap.josm.tools.ExceptionUtil;
    518
     19import mockit.Mock;
     20import mockit.MockUp;
    621import net.trajano.commons.testing.UtilityClassTestUtil;
    722
    … …  
    924 * Unit tests of {@link ExceptionDialogUtil} class.
    1025 */
     26@BasicPreferences
    1127class ExceptionDialogUtilTest {
    1228    /**
    … …  
    1834        UtilityClassTestUtil.assertUtilityClassWellDefined(ExceptionDialogUtil.class);
    1935    }
     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    }
    2069}
  • trunk/test/unit/org/openstreetmap/josm/gui/io/DownloadOpenChangesetsTaskTest.java

    r18991 r19707  
    88
    99import java.awt.GraphicsEnvironment;
    10 import java.net.URL;
    1110import java.util.HashMap;
    1211import java.util.Map;
    … …  
    1817import org.openstreetmap.josm.TestUtils;
    1918import org.openstreetmap.josm.data.UserIdentityManager;
    20 import org.openstreetmap.josm.gui.oauth.OAuthAuthorizationWizard;
    2119import org.openstreetmap.josm.testutils.annotations.BasicPreferences;
    2220import org.openstreetmap.josm.testutils.annotations.OsmApi;
    2321import org.openstreetmap.josm.testutils.mockers.JOptionPaneSimpleMocker;
    2422import 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;
    3023
    3124/**
    … …  
    3528@OsmApi(OsmApi.APIType.DEV)
    3629class 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         @Mock
    45         void showDialog() throws UserCancelException {
    46             this.called = true;
    47             throw new UserCancelException();
    48         }
    49 
    50         @Mock
    51         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 ui
    54                 // elements will fail with a mocked Window
    55                 this.called = true;
    56                 return;
    57             }
    58             // else we can allow a bit more of the code to be covered before we raise
    59             // UserCancelException in showDialog
    60             invocation.proceed(serverUrl);
    61         }
    62     }
    63 
    6430    /**
    6531     * Test of {@link DownloadOpenChangesetsTask} class when anonymous.
  • trunk/test/unit/org/openstreetmap/josm/gui/preferences/server/OAuthAuthenticationPreferencesPanelTest.java

    r19519 r19707  
    44import static org.junit.jupiter.api.Assertions.assertAll;
    55import static org.junit.jupiter.api.Assertions.assertEquals;
     6import static org.junit.jupiter.api.Assertions.assertFalse;
    67import static org.junit.jupiter.api.Assertions.assertNotNull;
    78import static org.junit.jupiter.api.Assertions.assertNull;
    89import static org.junit.jupiter.api.Assertions.assertSame;
     10import static org.junit.jupiter.api.Assertions.assertTrue;
    911import static org.junit.jupiter.api.Assertions.fail;
    1012import static org.openstreetmap.josm.tools.I18n.tr;
    1113
     14import java.awt.GraphicsEnvironment;
    1215import java.lang.reflect.Field;
    1316import java.net.Authenticator;
     17import java.net.URI;
    1418import java.util.ArrayList;
     19import java.util.Collections;
    1520import java.util.List;
     21import java.util.concurrent.CountDownLatch;
     22import java.util.concurrent.ExecutionException;
     23import java.util.stream.Stream;
    1624
    1725import javax.swing.JButton;
     26import javax.swing.JCheckBox;
     27import javax.swing.JOptionPane;
    1828import javax.swing.JPanel;
     29import javax.swing.JTextField;
    1930
    2031import org.junit.jupiter.api.AfterEach;
     32import org.junit.jupiter.api.Test;
    2133import org.junit.jupiter.params.ParameterizedTest;
    2234import org.junit.jupiter.params.provider.EnumSource;
     35import org.openstreetmap.josm.TestUtils;
    2336import org.openstreetmap.josm.data.oauth.OAuth20Exception;
    2437import org.openstreetmap.josm.data.oauth.OAuth20Parameters;
    2538import org.openstreetmap.josm.data.oauth.OAuth20Token;
    2639import org.openstreetmap.josm.data.oauth.OAuthAccessTokenHolder;
     40import org.openstreetmap.josm.data.oauth.OAuthParameters;
    2741import org.openstreetmap.josm.data.oauth.OAuthVersion;
     42import org.openstreetmap.josm.gui.MainApplication;
     43import org.openstreetmap.josm.gui.oauth.AdvancedOAuthPropertiesPanel;
     44import org.openstreetmap.josm.gui.util.GuiHelper;
     45import org.openstreetmap.josm.io.NetworkManager;
     46import org.openstreetmap.josm.io.OnlineResource;
    2847import org.openstreetmap.josm.io.OsmApi;
    2948import org.openstreetmap.josm.io.auth.CredentialsAgentException;
    3049import org.openstreetmap.josm.io.auth.CredentialsManager;
     50import org.openstreetmap.josm.io.remotecontrol.RemoteControl;
     51import org.openstreetmap.josm.spi.preferences.Config;
    3152import org.openstreetmap.josm.testutils.annotations.BasicPreferences;
     53import org.openstreetmap.josm.testutils.mockers.JOptionPaneSimpleMocker;
     54import org.openstreetmap.josm.testutils.mockers.OpenBrowserMocker;
     55import org.openstreetmap.josm.testutils.mockers.WindowMocker;
     56import org.openstreetmap.josm.tools.HttpClient;
    3257import org.openstreetmap.josm.tools.ReflectionUtils;
    3358
    … …  
    5681
    5782        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);
    5887    }
    5988
    … …  
    74103        assertSame(pnlAlreadyAuthorised.get(panel), holder.getComponent(0), "Authentication should now be set");
    75104        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);
    78106        assertEquals(tr("Remove token"), action.getText(), "The selected button should be for removing the token");
    79107        action.getAction().actionPerformed(null);
    80108        panel.saveToPreferences(); // Save to preferences should make the removal permanent
    81         // Ensure that the token holder has been reset for OAuth 1.0a
     109        // Ensure that the token holder has been reset
    82110        OAuthAccessTokenHolder.getInstance().clear();
    83111        OAuthAccessTokenHolder.getInstance().init(CredentialsManager.getInstance());
    … …  
    85113        panel.initFromPreferences();
    86114        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);
    87468    }
    88469
  • trunk/test/unit/org/openstreetmap/josm/io/OsmConnectionTest.java

    r19654 r19707  
    33
    44import static org.junit.jupiter.api.Assertions.assertEquals;
     5import static org.junit.jupiter.api.Assertions.assertFalse;
    56import static org.junit.jupiter.api.Assertions.assertNotNull;
    67import static org.junit.jupiter.api.Assertions.assertNull;
    … …  
    89import static org.junit.jupiter.api.Assertions.assertTrue;
    910
     11import java.awt.GraphicsEnvironment;
    1012import java.net.MalformedURLException;
    1113import java.net.URI;
     14import java.util.Collections;
    1215
    1316import javax.swing.JOptionPane;
    … …  
    1619import org.junit.jupiter.api.BeforeEach;
    1720import org.junit.jupiter.api.Test;
     21import org.openstreetmap.josm.TestUtils;
    1822import org.openstreetmap.josm.data.oauth.IOAuthParameters;
    1923import org.openstreetmap.josm.data.oauth.OAuth20Exception;
    … …  
    2125import org.openstreetmap.josm.data.oauth.OAuth20Token;
    2226import org.openstreetmap.josm.data.oauth.OAuthAccessTokenHolder;
     27import org.openstreetmap.josm.data.oauth.OAuthParameters;
    2328import org.openstreetmap.josm.data.oauth.OAuthVersion;
    2429import org.openstreetmap.josm.spi.preferences.Config;
    2530import org.openstreetmap.josm.testutils.annotations.BasicPreferences;
     31import org.openstreetmap.josm.testutils.mockers.JOptionPaneSimpleMocker;
     32import org.openstreetmap.josm.testutils.mockers.WindowMocker;
    2633import org.openstreetmap.josm.tools.HttpClient;
    2734
    … …  
    5562        OAuthAccessTokenHolder.getInstance().clear();
    5663        // 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);
    5866        Config.getPref().put("osm-server.url", null);
    5967    }
    … …  
    6472
    6573    /**
    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.
    6775     */
    6876    private static OAuth20Parameters rememberParameters() {
    6977        final OAuth20Parameters parameters = new OAuth20Parameters(CLIENT_ID, null, API_URL, API_URL, REDIRECT_URI);
     78        OAuthParameters.setUseDefault(API_URL, false);
    7079        parameters.rememberPreferences();
    7180        return parameters;
    … …  
    115124                () -> new TestConnection().addOAuth20AuthorizationHeader(client));
    116125        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");
    117127        assertTrue(thrown.getMessage().contains(API_URL), thrown.getMessage());
    118128        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"));
    119165    }
    120166
  • trunk/test/unit/org/openstreetmap/josm/io/auth/JosmPreferencesCredentialAgentTest.java

    r19652 r19707  
    22package org.openstreetmap.josm.io.auth;
    33
     4import static org.junit.jupiter.api.Assertions.assertEquals;
    45import static org.junit.jupiter.api.Assertions.assertFalse;
    56import static org.junit.jupiter.api.Assertions.assertNotNull;
    … …  
    2627
    2728    /**
    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.
    2931     * <p>
    30      * Non-regression test: both keys were built with the {@code parameters} prefix, so the token itself stayed in the
    31      * preferences in clear text. {@link CredentialsAgentTest#testLookupAndStoreOAuthTokens} did not notice, because a
    32      * lookup needs both keys and so already fails once the parameters are 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.
    3335     * @throws CredentialsAgentException if the token cannot be stored or removed
    3436     * @throws OAuth20Exception if the token cannot be built
    … …  
    4547                "{\"access_token\": \"a-secret-token\", \"token_type\": \"bearer\"}"));
    4648        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);
    4851
    4952        agent.storeOAuthAccessToken(host, null);
    5053
    5154        assertNull(Config.getPref().get(tokenKey, null), "the token is still stored in the preferences");
    52         assertNull(Config.getPref().get(parametersKey, null));
    5355        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);
    5559    }
    5660}
  • trunk/test/unit/org/openstreetmap/josm/testutils/JOSMTestRules.java

    r19519 r19707  
    5151import org.openstreetmap.josm.data.projection.Projections;
    5252import org.openstreetmap.josm.gui.MainApplication;
    53 import org.openstreetmap.josm.gui.oauth.OAuthAuthorizationWizard;
    5453import org.openstreetmap.josm.gui.preferences.imagery.ImageryPreferenceTestIT;
    5554import org.openstreetmap.josm.gui.util.GuiHelper;
    5655import org.openstreetmap.josm.io.OsmApi;
    5756import org.openstreetmap.josm.io.OsmApiInitializationException;
    58 import org.openstreetmap.josm.io.OsmConnection;
    5957import org.openstreetmap.josm.io.OsmTransferCanceledException;
    6058import org.openstreetmap.josm.spi.preferences.Config;
    … …  
    550548        // Setup callbacks
    551549        DeleteCommand.setDeletionCallback(DeleteAction.defaultDeletionCallback);
    552         OsmConnection.setOAuthAccessTokenFetcher(OAuthAuthorizationWizard::obtainAccessToken);
    553550        HttpClient.setFactory(Http1Client::new);
    554551
  • trunk/test/unit/org/openstreetmap/josm/testutils/annotations/JosmDefaults.java

    r19519 r19707  
    2121import org.openstreetmap.josm.data.UserIdentityManager;
    2222import org.openstreetmap.josm.data.osm.User;
    23 import org.openstreetmap.josm.gui.oauth.OAuthAuthorizationWizard;
    2423import org.openstreetmap.josm.gui.util.GuiHelper;
    25 import org.openstreetmap.josm.io.OsmConnection;
    2624import org.openstreetmap.josm.testutils.JOSMTestRules;
    2725import org.openstreetmap.josm.tools.Logging;
    … …  
    6058            // Setup callbacks
    6159            DeleteCommand.setDeletionCallback(DeleteAction.defaultDeletionCallback);
    62             OsmConnection.setOAuthAccessTokenFetcher(OAuthAuthorizationWizard::obtainAccessToken);
    6360        }
    6461
  • trunk/test/unit/org/openstreetmap/josm/tools/ExceptionUtilTest.java

    r19227 r19707  
    33
    44import static org.junit.jupiter.api.Assertions.assertEquals;
     5import static org.junit.jupiter.api.Assertions.assertTrue;
    56
    67import java.io.IOException;
    … …  
    279280
    280281    /**
     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    /**
    281294     * Test of {@link ExceptionUtil#explainNestedIllegalDataException} method.
    282295     */
Note: See TracChangeset for help on using the changeset viewer.