001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.data.oauth;
003
004import java.io.ByteArrayInputStream;
005import java.io.IOException;
006import java.io.UncheckedIOException;
007import java.nio.charset.StandardCharsets;
008import java.util.Objects;
009
010import jakarta.json.Json;
011import jakarta.json.JsonObject;
012import jakarta.json.JsonObjectBuilder;
013import jakarta.json.JsonReader;
014import jakarta.json.JsonStructure;
015import jakarta.json.JsonValue;
016
017import org.openstreetmap.josm.spi.preferences.Config;
018import org.openstreetmap.josm.tools.Logging;
019import org.openstreetmap.josm.tools.Utils;
020
021/**
022 * Parameters for OAuth 2.0
023 * @author Taylor Smock
024 * @since 18650
025 */
026public final class OAuth20Parameters implements IOAuthParameters {
027    private static final String REDIRECT_URI = "redirect_uri";
028    private static final String CLIENT_ID = "client_id";
029    private static final String CLIENT_SECRET = "client_secret";
030    private static final String TOKEN_URL = "token_url";
031    private static final String AUTHORIZE_URL = "authorize_url";
032    private static final String API_URL = "api_url";
033    private final String redirectUri;
034    private final String clientSecret;
035    private final String clientId;
036    private final String tokenUrl;
037    private final String authorizeUrl;
038    private final String apiUrl;
039
040    /**
041     * Recreate a parameter object from a JSON string
042     * @param jsonString The JSON string with the required data
043     */
044    public OAuth20Parameters(String jsonString) {
045        try (ByteArrayInputStream bais = new ByteArrayInputStream(jsonString.getBytes(StandardCharsets.UTF_8));
046             JsonReader reader = Json.createReader(bais)) {
047            JsonStructure structure = reader.read();
048            if (structure.getValueType() != JsonValue.ValueType.OBJECT) {
049                throw new IllegalArgumentException("Invalid JSON object: " + jsonString);
050            }
051            JsonObject jsonObject = structure.asJsonObject();
052            this.redirectUri = jsonObject.getString(REDIRECT_URI);
053            this.clientId = jsonObject.getString(CLIENT_ID);
054            this.clientSecret = jsonObject.getString(CLIENT_SECRET, null);
055            this.tokenUrl = jsonObject.getString(TOKEN_URL);
056            this.authorizeUrl = jsonObject.getString(AUTHORIZE_URL);
057            this.apiUrl = jsonObject.getString(API_URL);
058        } catch (IOException e) {
059            // This should literally never happen -- ByteArrayInputStream does not do *anything* in the close method.
060            throw new UncheckedIOException(e);
061        }
062    }
063
064    /**
065     * Create a new OAuth parameter object
066     * @param clientId The client id. May not be {@code null}.
067     * @param clientSecret The client secret. May be {@code null}. Not currently used.
068     * @param baseUrl The base url. This assumes that the endpoints are {@code /token} and {@code /authorize}.
069     * @param apiUrl The API url
070     * @param redirectUri The redirect URI for the client.
071     */
072    public OAuth20Parameters(String clientId, String clientSecret, String baseUrl, String apiUrl, String redirectUri) {
073        this(clientId, clientSecret, baseUrl + "/token", baseUrl + "/authorize", apiUrl, redirectUri);
074    }
075
076    /**
077     * Create a new OAuth parameter object
078     * @param clientId The client id.
079     * @param clientSecret The client secret. May be {@code null}. Not currently used.
080     * @param tokenUrl The token request URL (RFC6749 4.4.2)
081     * @param authorizeUrl The authorization request URL (RFC6749 4.1.1)
082     * @param apiUrl The API url
083     * @param redirectUri The redirect URI for the client.
084     */
085    public OAuth20Parameters(String clientId, String clientSecret, String tokenUrl, String authorizeUrl, String apiUrl, String redirectUri) {
086        Objects.requireNonNull(authorizeUrl, "authorizeUrl");
087        Objects.requireNonNull(clientId, "clientId");
088        Objects.requireNonNull(redirectUri, "redirectUri");
089        Objects.requireNonNull(tokenUrl, "tokenUrl");
090        Objects.requireNonNull(apiUrl, "apiUrl");
091        // Alternatively, we could try using rfc8414 ( /.well-known/oauth-authorization-server ), but OSM (doorkeeper) doesn't support it.
092        this.redirectUri = redirectUri;
093        this.clientId = clientId;
094        this.clientSecret = clientSecret;
095        this.tokenUrl = tokenUrl;
096        this.authorizeUrl = authorizeUrl;
097        this.apiUrl = apiUrl;
098    }
099
100    @Override
101    public String getAccessTokenUrl() {
102        return this.tokenUrl;
103    }
104
105    @Override
106    public String getAuthorizationUrl() {
107        return this.authorizeUrl;
108    }
109
110    @Override
111    public OAuthVersion getOAuthVersion() {
112        return OAuthVersion.OAuth20;
113    }
114
115    @Override
116    public String getClientId() {
117        return this.clientId;
118    }
119
120    @Override
121    public String getClientSecret() {
122        return this.clientSecret;
123    }
124
125    @Override
126    public String getRedirectUri() {
127        return this.redirectUri;
128    }
129
130    @Override
131    public String getApiUrl() {
132        return this.apiUrl;
133    }
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     */
141    @Override
142    public void rememberPreferences() {
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        }
155    }
156
157    @Override
158    public String toPreferencesString() {
159        JsonObjectBuilder builder = Json.createObjectBuilder();
160        builder.add(CLIENT_ID, this.clientId);
161        builder.add(REDIRECT_URI, this.redirectUri);
162        if (this.apiUrl != null) builder.add(API_URL, this.apiUrl);
163        if (this.authorizeUrl != null) builder.add(AUTHORIZE_URL, this.authorizeUrl);
164        if (this.clientSecret != null) builder.add(CLIENT_SECRET, this.clientSecret);
165        if (this.tokenUrl != null) builder.add(TOKEN_URL, this.tokenUrl);
166        return builder.build().toString();
167    }
168
169    @Override
170    public int hashCode() {
171        return Objects.hash(this.apiUrl, this.authorizeUrl, this.tokenUrl, this.clientId, this.clientSecret, this.redirectUri);
172    }
173
174    @Override
175    public boolean equals(Object obj) {
176        if (obj != null && this.getClass() == obj.getClass()) {
177            OAuth20Parameters other = (OAuth20Parameters) obj;
178            return Objects.equals(this.clientSecret, other.clientSecret) &&
179                    Objects.equals(this.clientId, other.clientId) &&
180                    Objects.equals(this.redirectUri, other.redirectUri) &&
181                    Objects.equals(this.tokenUrl, other.tokenUrl) &&
182                    Objects.equals(this.authorizeUrl, other.authorizeUrl) &&
183                    Objects.equals(this.apiUrl, other.apiUrl);
184        }
185        return false;
186    }
187}