001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.data.oauth;
003
004import static org.openstreetmap.josm.tools.I18n.tr;
005
006import java.awt.Dimension;
007import java.io.IOException;
008import java.net.MalformedURLException;
009import java.net.URL;
010import java.nio.charset.StandardCharsets;
011import java.security.MessageDigest;
012import java.security.NoSuchAlgorithmException;
013import java.util.Base64;
014import java.util.Map;
015import java.util.Objects;
016import java.util.Optional;
017import java.util.UUID;
018import java.util.function.Consumer;
019
020import javax.swing.JOptionPane;
021import javax.swing.JScrollPane;
022
023import org.openstreetmap.josm.gui.MainApplication;
024import org.openstreetmap.josm.gui.datatransfer.ClipboardUtils;
025import org.openstreetmap.josm.gui.util.GuiHelper;
026import org.openstreetmap.josm.gui.widgets.HtmlPanel;
027import org.openstreetmap.josm.io.remotecontrol.handler.AuthorizationHandler;
028import org.openstreetmap.josm.io.remotecontrol.handler.RequestHandler;
029import org.openstreetmap.josm.tools.HttpClient;
030import org.openstreetmap.josm.tools.Utils;
031import org.openstreetmap.josm.tools.JosmRuntimeException;
032import org.openstreetmap.josm.tools.OpenBrowser;
033
034/**
035 * Authorize the application
036 * @since 18650
037 */
038public class OAuth20Authorization implements IOAuthAuthorization {
039    /**
040     * See <a href="https://www.rfc-editor.org/rfc/rfc7636">RFC7636</a>: PKCE
041     * @param cryptographicallyRandomString A cryptographically secure string
042     * @return The S256 bytes
043     */
044    private static String getPKCES256CodeChallenge(String cryptographicallyRandomString) {
045        // S256: code_challenge = BASE64URL-ENCODE(SHA256(ASCII(code_verifier)))
046        try {
047            byte[] encodedBytes = cryptographicallyRandomString.getBytes(StandardCharsets.US_ASCII);
048            MessageDigest digest = MessageDigest.getInstance("SHA-256");
049            return new String(Base64.getUrlEncoder().encode(digest.digest(encodedBytes)), StandardCharsets.US_ASCII)
050                    .replace("=", "").replace("+", "-").replace("/", "_");
051        } catch (NoSuchAlgorithmException e) {
052            throw new JosmRuntimeException(e);
053        }
054    }
055
056    @Override
057    public void authorize(IOAuthParameters parameters, Consumer<Optional<IOAuthToken>> consumer, Enum<?>... scopes) {
058        final String state = UUID.randomUUID().toString();
059        final String codeVerifier = UUID.randomUUID().toString(); // Cryptographically random string (ASCII)
060        final String s256CodeChallenge = getPKCES256CodeChallenge(codeVerifier);
061
062        // Enable authorization remote control
063        new AuthorizationHandler().getPermissionPreference().put(true);
064        String url = parameters.getAuthorizationUrl(state, scopes)
065                + "&code_challenge_method=S256&code_challenge=" + s256CodeChallenge;
066        AuthorizationHandler.addAuthorizationConsumer(state, new OAuth20AuthorizationHandler(state, codeVerifier, parameters, consumer));
067        GuiHelper.runInEDT(() -> showUrlOpenFailure(url, OpenBrowser.displayUrl(url)));
068    }
069
070    /**
071     * Show a message if a URL fails to open
072     * @param url The URL that failed to open
073     * @param error The message indicating why the URL failed to open; if {@code null}, no message is shown.
074     */
075    private static void showUrlOpenFailure(String url, String error) {
076        if (error != null) {
077            final HtmlPanel textField = new HtmlPanel("<html><body>"
078                    + tr("The web browser failed to open with the following error: \"{0}\".<br>\n"
079                            + "Please open the following url:<br>\n"
080                            + "<a href=\"{1}\">{1}</a><br>\n"
081                            + "Should we copy the URL to the clipboard?", error, url)
082                    + "</body></html>");
083            textField.enableClickableHyperlinks();
084            final JScrollPane scrollPane = new JScrollPane(textField);
085            // Ensure that the scroll pane doesn't extend too much or too little.
086            // For now, assume that the user hasn't made the main JOSM frame beyond monitors.
087            scrollPane.setPreferredSize(new Dimension(Math.min(textField.getPreferredSize().width + 32,
088                    MainApplication.getMainFrame().getWidth() - 240 /* warning image + buffer */),
089                    textField.getPreferredSize().height + scrollPane.getHorizontalScrollBar().getPreferredSize().height * 2));
090            GuiHelper.prepareResizeableOptionPane(scrollPane, scrollPane.getPreferredSize());
091            int answer = JOptionPane.showConfirmDialog(MainApplication.getMainFrame(), scrollPane, tr("Failed to open browser"),
092                    JOptionPane.YES_NO_OPTION, JOptionPane.ERROR_MESSAGE);
093            if (answer == JOptionPane.YES_OPTION) {
094                ClipboardUtils.copyString(url);
095            }
096        }
097    }
098
099    private static class OAuth20AuthorizationHandler implements AuthorizationHandler.AuthorizationConsumer {
100
101        private final String state;
102        private final IOAuthParameters parameters;
103        private final Consumer<Optional<IOAuthToken>> consumer;
104        private final String codeVerifier;
105
106        OAuth20AuthorizationHandler(String state, String codeVerifier, IOAuthParameters parameters, Consumer<Optional<IOAuthToken>> consumer) {
107            this.state = state;
108            this.parameters = parameters;
109            this.consumer = consumer;
110            this.codeVerifier = codeVerifier;
111        }
112
113        @Override
114        public void validateRequest(String sender, String request, Map<String, String> args)
115                throws RequestHandler.RequestHandlerBadRequestException {
116            String argState = args.get("state");
117            if (!Objects.equals(this.state, argState)) {
118                throw new RequestHandler.RequestHandlerBadRequestException(
119                        tr("Mismatched state: Expected {0} but got {1}", this.state, argState));
120            }
121        }
122
123        @Override
124        public AuthorizationHandler.ResponseRecord handleRequest(String sender, String request, Map<String, String> args)
125                throws RequestHandler.RequestHandlerErrorException, RequestHandler.RequestHandlerBadRequestException {
126            String code = args.get("code");
127            try {
128                HttpClient tradeCodeForToken = HttpClient.create(new URL(parameters.getAccessTokenUrl()), "POST");
129                // A confidential client (the default when registering an application on
130                // openstreetmap-website) must present its secret at the token endpoint;
131                // the built-in OSM application is a public client and has none.
132                String clientSecret = parameters.getClientSecret();
133                tradeCodeForToken.setRequestBody(("grant_type=authorization_code&client_id=" + parameters.getClientId()
134                        + (!Utils.isEmpty(clientSecret) ? "&client_secret=" + Utils.encodeUrl(clientSecret) : "")
135                        + "&redirect_uri=" + parameters.getRedirectUri()
136                        + "&code=" + code
137                        + (this.codeVerifier != null ? "&code_verifier=" + this.codeVerifier : "")
138                ).getBytes(StandardCharsets.UTF_8));
139                tradeCodeForToken.setHeader("Content-Type", "application/x-www-form-urlencoded");
140                try {
141                    tradeCodeForToken.connect();
142                    HttpClient.Response response = tradeCodeForToken.getResponse();
143                    if (response.getResponseCode() >= 400) {
144                        // Doorkeeper answers a rejected exchange with a JSON error body, but an
145                        // authentication failure can come back with none - say what the server said
146                        String body = response.fetchContent();
147                        throw new OAuth20Exception(tr("The server refused the token request: HTTP {0} {1}",
148                                response.getResponseCode(), Utils.isEmpty(body) ? response.getResponseMessage() : body));
149                    }
150                    OAuth20Token oAuth20Token = new OAuth20Token(parameters, response.getContentReader());
151                    consumer.accept(Optional.of(oAuth20Token));
152                } catch (IOException | OAuth20Exception e) {
153                    consumer.accept(Optional.empty());
154                    throw new RequestHandler.RequestHandlerErrorException(e);
155                } finally {
156                    tradeCodeForToken.disconnect();
157                }
158            } catch (MalformedURLException e) {
159                consumer.accept(Optional.empty());
160                throw new RequestHandler.RequestHandlerBadRequestException(e);
161            }
162            return null;
163        }
164    }
165}