001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.io.remotecontrol.handler;
003
004import java.util.HashMap;
005import java.util.Map;
006import java.util.Objects;
007import java.util.Optional;
008import java.util.stream.Collectors;
009
010import org.openstreetmap.josm.data.preferences.BooleanProperty;
011import org.openstreetmap.josm.io.remotecontrol.PermissionPrefWithDefault;
012
013/**
014 * Handle authorization requests (mostly OAuth)
015 * @since 18650
016 */
017public class AuthorizationHandler extends RequestHandler {
018
019    /**
020     * The actual authorization consumer/handler
021     */
022    public interface AuthorizationConsumer {
023        /**
024         * Validate the request
025         * @param args The GET request arguments
026         * @param request The request URL without "GET".
027         * @param sender who sent the request? the host from referer header or IP of request sender
028         * @throws RequestHandlerBadRequestException if the request is invalid
029         * @see RequestHandler#validateRequest()
030         */
031        void validateRequest(String sender, String request, Map<String, String> args)
032                throws RequestHandlerBadRequestException;
033
034        /**
035         * Handle the request. Any time-consuming operation must be performed asynchronously to avoid delaying the HTTP response.
036         * @param args The GET request arguments
037         * @param request The request URL without "GET".
038         * @param sender who sent the request? the host from referer header or IP of request sender
039         * @return The response to show the user. May be {@code null}.
040         * @throws RequestHandlerErrorException if an error occurs while processing the request
041         * @throws RequestHandlerBadRequestException if the request is invalid
042         * @see RequestHandler#handleRequest()
043         */
044        ResponseRecord handleRequest(String sender, String request, Map<String, String> args)
045                throws RequestHandlerErrorException, RequestHandlerBadRequestException;
046    }
047
048    /**
049     * A basic record for changing responses
050     */
051    public static final class ResponseRecord {
052        private final String content;
053        private final String type;
054
055        /**
056         * Create a new record
057         * @param content The content to show the user
058         * @param type The content mime type
059         */
060        public ResponseRecord(String content, String type) {
061            this.content = content;
062            this.type = type;
063        }
064
065        /**
066         * Get the content for the response
067         * @return The content as a string
068         */
069        public String content() {
070            return this.content;
071        }
072
073        /**
074         * Get the type for the response
075         * @return The response mime type
076         */
077        public String type() {
078            return this.type;
079        }
080    }
081
082    /**
083     * The remote control command
084     */
085    public static final String command = "oauth_authorization";
086
087    private static final BooleanProperty PROPERTY = new BooleanProperty("remotecontrol.permission.authorization", false);
088    private static final Map<String, AuthorizationConsumer> AUTHORIZATION_CONSUMERS = new HashMap<>();
089
090    private AuthorizationConsumer consumer;
091    /**
092     * Add an authorization consumer.
093     * @param state The unique state for each request (for OAuth, this would be the {@code state} parameter)
094     * @param consumer The consumer of the response
095     */
096    public static synchronized void addAuthorizationConsumer(String state, AuthorizationConsumer consumer) {
097        if (AUTHORIZATION_CONSUMERS.containsKey(state)) {
098            throw new IllegalArgumentException("Cannot add multiple consumers for one authorization state");
099        }
100        AUTHORIZATION_CONSUMERS.put(state, consumer);
101    }
102
103    @Override
104    protected void validateRequest() throws RequestHandlerBadRequestException {
105        boolean clearAll = false;
106        for (Map.Entry<String, AuthorizationConsumer> entry : AUTHORIZATION_CONSUMERS.entrySet()) {
107            if (Objects.equals(this.args.get("state"), entry.getKey())) {
108                if (this.consumer == null) {
109                    this.consumer = entry.getValue();
110                } else {
111                    // Remove all authorization consumers. Someone might be playing games.
112                    clearAll = true;
113                }
114            }
115        }
116        if (clearAll) {
117            AUTHORIZATION_CONSUMERS.clear();
118            this.consumer = null;
119            throw new RequestHandlerBadRequestException("Multiple states for authorization");
120        }
121
122        if (this.consumer == null) {
123            throw new RequestHandlerBadRequestException("Unknown state for authorization");
124        }
125        this.consumer.validateRequest(this.sender, this.request, this.args);
126    }
127
128    @Override
129    protected void handleRequest() throws RequestHandlerErrorException, RequestHandlerBadRequestException {
130        ResponseRecord response = this.consumer.handleRequest(this.sender, this.request, this.args);
131        if (response != null) {
132            this.content = Optional.ofNullable(response.content()).orElse(this.content);
133            this.contentType = Optional.ofNullable(response.type()).orElse(this.contentType);
134        }
135        // Only ever allow a consumer to be used once
136        AUTHORIZATION_CONSUMERS.entrySet().stream().filter(entry -> Objects.equals(this.consumer, entry.getValue()))
137                .map(Map.Entry::getKey).collect(Collectors.toList()).forEach(AUTHORIZATION_CONSUMERS::remove);
138        this.consumer = null;
139    }
140
141    @Override
142    public String getPermissionMessage() {
143        return "Allow OAuth remote control to set credentials";
144    }
145
146    @Override
147    public PermissionPrefWithDefault getPermissionPref() {
148        return null;
149    }
150
151    public BooleanProperty getPermissionPreference() {
152        return PROPERTY;
153    }
154
155    @Override
156    public String[] getMandatoryParams() {
157        return new String[] {"code", "state"};
158    }
159}