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.InputStreamReader; 007import java.io.Reader; 008import java.net.URI; 009import java.net.URL; 010import java.nio.charset.StandardCharsets; 011import java.time.Instant; 012 013import jakarta.json.Json; 014import jakarta.json.JsonObject; 015import jakarta.json.JsonObjectBuilder; 016import jakarta.json.JsonReader; 017import jakarta.json.JsonStructure; 018import jakarta.json.JsonValue; 019 020import org.openstreetmap.josm.tools.HttpClient; 021import org.openstreetmap.josm.tools.JosmRuntimeException; 022import org.openstreetmap.josm.tools.Utils; 023 024/** 025 * Token holder for OAuth 2.0 026 * @author Taylor Smock 027 * @since 18650 028 */ 029public final class OAuth20Token implements IOAuthToken { 030 private static final String ACCESS_TOKEN = "access_token"; 031 private static final String CREATED_AT = "created_at"; 032 private static final String EXPIRES_IN = "expires_in"; 033 private static final String REFRESH_TOKEN = "refresh_token"; 034 private static final String SCOPE = "scope"; 035 private static final String TOKEN_TYPE = "token_type"; 036 private final String accessToken; 037 private final String tokenType; 038 private final int expiresIn; 039 private final String refreshToken; 040 private final String[] scopes; 041 private final Instant createdAt; 042 private final IOAuthParameters oauthParameters; 043 044 /** 045 * Create a new OAuth token 046 * @param oauthParameters The parameters for the OAuth token 047 * @param json The stored JSON for the token 048 * @throws OAuth20Exception If the JSON creates an invalid token 049 */ 050 public OAuth20Token(IOAuthParameters oauthParameters, String json) throws OAuth20Exception { 051 this(oauthParameters, new InputStreamReader(new ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8)), StandardCharsets.UTF_8)); 052 } 053 054 /** 055 * Create a bearer token from the access token alone, such as a token issued outside JOSM and pasted by the user. 056 * It has no refresh token, and works with nothing else: the parameters only need the API URL the token is for. 057 * @param oauthParameters The parameters for the OAuth token 058 * @param accessToken The access token 059 * @return The bearer token 060 * @since 19707 061 */ 062 public static OAuth20Token fromAccessToken(IOAuthParameters oauthParameters, String accessToken) { 063 final String json = Json.createObjectBuilder() 064 .add(ACCESS_TOKEN, accessToken) 065 .add(TOKEN_TYPE, "bearer") 066 .build().toString(); 067 try { 068 return new OAuth20Token(oauthParameters, json); 069 } catch (OAuth20Exception e) { 070 // both required fields are present 071 throw new JosmRuntimeException(e); 072 } 073 } 074 075 OAuth20Token(IOAuthParameters oauthParameters, Reader bufferedReader) throws OAuth20Exception { 076 this.oauthParameters = oauthParameters; 077 try (JsonReader reader = Json.createReader(bufferedReader)) { 078 JsonStructure structure = reader.read(); 079 if (structure.getValueType() != JsonValue.ValueType.OBJECT 080 || !structure.asJsonObject().containsKey(ACCESS_TOKEN) 081 || !structure.asJsonObject().containsKey(TOKEN_TYPE)) { 082 if (structure.getValueType() == JsonValue.ValueType.OBJECT 083 && structure.asJsonObject().containsKey("error")) { 084 throw new OAuth20Exception(structure.asJsonObject()); 085 } else { 086 throw new OAuth20Exception("Either " + ACCESS_TOKEN + " or " + TOKEN_TYPE + " is not present: " + structure); 087 } 088 } 089 JsonObject object = structure.asJsonObject(); 090 this.accessToken = object.getString(ACCESS_TOKEN); 091 this.tokenType = object.getString(TOKEN_TYPE); 092 this.expiresIn = object.getInt(EXPIRES_IN, Integer.MAX_VALUE); 093 this.refreshToken = object.getString(REFRESH_TOKEN, null); 094 this.scopes = object.getString(SCOPE, "").split(" "); 095 if (object.containsKey(CREATED_AT)) { 096 this.createdAt = Instant.ofEpochSecond(object.getJsonNumber(CREATED_AT).longValue()); 097 } else { 098 this.createdAt = Instant.now(); 099 } 100 } 101 } 102 103 @Override 104 public void sign(HttpClient client) throws OAuthException { 105 if (!Utils.isStripEmpty(this.oauthParameters.getApiUrl()) 106 && !this.oauthParameters.getApiUrl().contains(client.getURL().getHost())) { 107 String host = URI.create(this.oauthParameters.getAccessTokenUrl()).getHost(); 108 throw new IllegalArgumentException("Cannot sign URL with token for different host: Expected " + host 109 + " but got " + client.getURL().getHost()); 110 } 111 if (this.getBearerToken() != null) { 112 client.setHeader("Authorization", "Bearer " + this.getBearerToken()); 113 return; 114 } 115 throw new OAuth20Exception("Unknown token type: " + this.tokenType); 116 } 117 118 /** 119 * Get the OAuth 2.0 bearer token 120 * @return The bearer token. May return {@code null} if the token type is not a bearer type. 121 */ 122 public String getBearerToken() { 123 if ("bearer".equalsIgnoreCase(this.tokenType)) { 124 return this.accessToken; 125 } 126 return null; 127 } 128 129 @Override 130 public String toPreferencesString() { 131 final OAuth20Token tokenToSave; 132 if (shouldRefresh()) { 133 tokenToSave = refresh(); 134 } else { 135 tokenToSave = this; 136 } 137 JsonObjectBuilder jsonObjectBuilder = Json.createObjectBuilder(); 138 jsonObjectBuilder.add(ACCESS_TOKEN, tokenToSave.accessToken); 139 jsonObjectBuilder.add(TOKEN_TYPE, tokenToSave.tokenType); 140 if (tokenToSave.createdAt != null) { 141 jsonObjectBuilder.add(CREATED_AT, tokenToSave.createdAt.getEpochSecond()); 142 } 143 if (tokenToSave.expiresIn != Integer.MAX_VALUE) { 144 jsonObjectBuilder.add(EXPIRES_IN, tokenToSave.expiresIn); 145 } 146 if (tokenToSave.refreshToken != null) { 147 jsonObjectBuilder.add(REFRESH_TOKEN, tokenToSave.refreshToken); 148 } 149 if (tokenToSave.scopes.length > 0) { 150 jsonObjectBuilder.add(SCOPE, String.join(" ", tokenToSave.scopes)); 151 } 152 return jsonObjectBuilder.build().toString(); 153 } 154 155 @Override 156 public OAuthVersion getOAuthType() { 157 return OAuthVersion.OAuth20; 158 } 159 160 @Override 161 public IOAuthParameters getParameters() { 162 return this.oauthParameters; 163 } 164 165 /** 166 * Check if the token should be refreshed 167 * @return {@code true} if the token should be refreshed 168 */ 169 boolean shouldRefresh() { 170 return this.refreshToken != null && this.expiresIn != Integer.MAX_VALUE 171 // We should refresh the token when 10% of its lifespan has been spent. 172 // We aren't an application that will be used every day by every user. 173 && this.createdAt.getEpochSecond() + this.expiresIn < Instant.now().getEpochSecond() - this.expiresIn * 9L / 10; 174 } 175 176 /** 177 * Refresh the OAuth 2.0 token 178 * @return The new token to use 179 */ 180 OAuth20Token refresh() { 181 // This bit isn't necessarily OAuth 2.1 compliant. Spec isn't finished yet, but 182 // refresh tokens will either be sender constrained or some kind of rotation or both. 183 // This refresh code handles rotation, mostly by creating a new OAuth20Token. :) 184 // For sender constrained, it will likely allow self-signed certificates (RFC8705). 185 // Note: OSM doesn't have age limits on their tokens, at time of writing. 186 String refresh = "grant_type=refresh_token&refresh_token=" + this.refreshToken; 187 if (this.scopes.length > 0) { 188 refresh += "&scope=" + String.join(" ", this.scopes); 189 } 190 HttpClient client = null; 191 try { 192 client = HttpClient.create(new URL(this.oauthParameters.getAccessTokenUrl()), "POST"); 193 client.setRequestBody(refresh.getBytes(StandardCharsets.UTF_8)); 194 client.connect(); 195 HttpClient.Response response = client.getResponse(); 196 return new OAuth20Token(this.oauthParameters, response.getContentReader()); 197 } catch (IOException | OAuth20Exception e) { 198 throw new JosmRuntimeException(e); 199 } finally { 200 if (client != null) { 201 client.disconnect(); 202 } 203 } 204 } 205}