Ticket #25141: http-log-credentials.patch
| File http-log-credentials.patch, 23.2 KB (added by , 110 minutes ago) |
|---|
-
src/org/openstreetmap/josm/actions/ShowStatusReportAction.java
diff --git src/org/openstreetmap/josm/actions/ShowStatusReportAction.java src/org/openstreetmap/josm/actions/ShowStatusReportAction.java index ec1921344b..9acf29315f 100644
import org.openstreetmap.josm.tools.Logging; 51 51 import org.openstreetmap.josm.tools.PlatformHookUnixoid; 52 52 import org.openstreetmap.josm.tools.PlatformManager; 53 53 import org.openstreetmap.josm.tools.Shortcut; 54 import org.openstreetmap.josm.tools.TextUtils; 54 55 import org.openstreetmap.josm.tools.Utils; 55 56 import org.openstreetmap.josm.tools.bugreport.BugReportSender; 56 57 … … public final class ShowStatusReportAction extends JosmAction { 308 309 } 309 310 } 310 311 311 private static String valueCleanup(Object value) { 312 /** 313 * Shortens and removes private information from a preference value used for status report, among them the API keys 314 * and tokens of URLs, e.g. of custom imagery. 315 * @param value preference value to cleanup 316 * @return shortened/anonymized value 317 */ 318 static String valueCleanup(Object value) { 319 return valueCleanupStripped(stripUrls(value)); 320 } 321 322 private static Object stripUrls(Object value) { 323 if (value instanceof String) { 324 return TextUtils.stripUrl((String) value); 325 } else if (value instanceof Map<?, ?>) { 326 Map<Object, Object> map = new LinkedHashMap<>(); 327 ((Map<?, ?>) value).forEach((k, v) -> map.put(k, stripUrls(v))); 328 return map; 329 } else if (value instanceof Collection<?>) { 330 return ((Collection<?>) value).stream().map(ShowStatusReportAction::stripUrls).collect(Collectors.toList()); 331 } 332 return value; 333 } 334 335 private static String valueCleanupStripped(Object value) { 312 336 String valueString = value.toString(); 313 337 if (valueString.length() > 512 && value instanceof Collection<?>) { 314 338 valueString = ((Collection<?>) value).stream().map(v -> { -
src/org/openstreetmap/josm/io/remotecontrol/RequestProcessor.java
diff --git src/org/openstreetmap/josm/io/remotecontrol/RequestProcessor.java src/org/openstreetmap/josm/io/remotecontrol/RequestProcessor.java index 4d3dfd8f0a..6333fc05f5 100644
import org.openstreetmap.josm.io.remotecontrol.handler.RequestHandler.RequestHan 52 52 import org.openstreetmap.josm.io.remotecontrol.handler.RequestHandler.RequestHandlerOsmApiException; 53 53 import org.openstreetmap.josm.io.remotecontrol.handler.VersionHandler; 54 54 import org.openstreetmap.josm.tools.Logging; 55 import org.openstreetmap.josm.tools.TextUtils; 55 56 import org.openstreetmap.josm.tools.Utils; 56 57 57 58 /** … … public class RequestProcessor extends Thread { 224 225 sendInternalError(out, null); 225 226 return; 226 227 } 227 Logging.info("RemoteControl received: " + get);228 Logging.info("RemoteControl received: " + TextUtils.stripUrl(get)); // e.g. an OAuth 2.0 authorization code 228 229 229 230 StringTokenizer st = new StringTokenizer(get); 230 231 if (!st.hasMoreTokens()) { -
src/org/openstreetmap/josm/tools/HttpClient.java
diff --git src/org/openstreetmap/josm/tools/HttpClient.java src/org/openstreetmap/josm/tools/HttpClient.java index 64f329768d..40fd0c3a65 100644
public abstract class HttpClient { 157 157 ConnectionResponse cr; 158 158 try { 159 159 if (Logging.isDebugEnabled()) { 160 Logging.debug("REQUEST HEADERS: {0}", headers);160 Logging.debug("REQUEST HEADERS: {0}", TextUtils.stripHeaders(headers)); 161 161 } 162 162 cr = performConnection(); 163 163 final boolean hasReason = !Utils.isEmpty(reasonForRequest); … … public abstract class HttpClient { 171 171 ); 172 172 if (Logging.isDebugEnabled()) { 173 173 try { 174 Logging.debug("RESPONSE HEADERS: {0}", cr.getHeaderFields());174 Logging.debug("RESPONSE HEADERS: {0}", TextUtils.stripHeaders(cr.getHeaderFields())); 175 175 } catch (IllegalArgumentException e) { 176 176 Logging.warn(e); 177 177 } … … public abstract class HttpClient { 246 246 } 247 247 248 248 protected final void logRequestBody() { 249 logRequest("{0} {1} ({2}) ...", requestMethod, url, Utils.getSizeString(requestBody.length, Locale.getDefault())); 249 logRequest("{0} {1} ({2}) ...", requestMethod, TextUtils.stripUrl(url.toString()), 250 Utils.getSizeString(requestBody.length, Locale.getDefault())); 250 251 if (Logging.isTraceEnabled() && hasRequestBody()) { 251 Logging.trace("BODY: {0}", new String(requestBody, StandardCharsets.UTF_8)); 252 final String body = new String(requestBody, StandardCharsets.UTF_8); 253 final String contentType = headers.get("Content-Type"); 254 // a form-encoded body has the syntax of a query, e.g. an OAuth 2.0 token request with the client secret 255 Logging.trace("BODY: {0}", contentType != null && contentType.contains("application/x-www-form-urlencoded") 256 ? TextUtils.stripUrl(body) : body); 252 257 } 253 258 } 254 259 -
src/org/openstreetmap/josm/tools/TextUtils.java
diff --git src/org/openstreetmap/josm/tools/TextUtils.java src/org/openstreetmap/josm/tools/TextUtils.java index a30d7e35ff..f7c56cbc40 100644
1 1 // License: GPL. For details, see LICENSE file. 2 2 package org.openstreetmap.josm.tools; 3 3 4 import java.util.LinkedHashMap; 5 import java.util.List; 6 import java.util.Locale; 7 import java.util.Map; 8 import java.util.regex.Pattern; 9 import java.util.stream.Collectors; 10 4 11 /** 5 12 * Text/String utils. 6 13 * @since 13978 7 14 */ 8 15 public final class TextUtils { 9 16 17 /** What private information is replaced with */ 18 private static final String STRIPPED = "...stripped..."; 19 /** 20 * The parameters which are private: API keys and tokens, and OAuth 2.0 client secrets, authorization codes and 21 * their verifiers, and passwords. {@code code} is only matched as a whole name, so as not to strip e.g. a postcode. 22 * A value ends at white space too, so that what follows a URL in a log line is kept. 23 */ 24 private static final Pattern PRIVATE_PARAMETERS = 25 Pattern.compile("(token|key|connectId|secret|password|(?<![\\w-])code|verifier)=[^&\\s]+"); 26 10 27 private TextUtils() { 11 28 // Hide default constructor for utils classes 12 29 } … … public final class TextUtils { 22 39 } 23 40 24 41 /** 25 * Remove privacy related parts from output URL 42 * Remove privacy related parts from output URL. 43 * <p> 44 * This works for a form-encoded ({@code application/x-www-form-urlencoded}) request body as well, which has the 45 * syntax of a query, such as an OAuth 2.0 token request with its client secret. 26 46 * @param url Unmodified URL 27 47 * @return Stripped URL (privacy related issues removed) 28 48 * @since 18652 29 49 */ 30 50 public static String stripUrl(String url) { 31 return url.replaceAll("(token|key|connectId)=[^&]+", "$1=...stripped..."); 51 return PRIVATE_PARAMETERS.matcher(url).replaceAll("$1=" + STRIPPED); 52 } 53 54 /** 55 * Remove privacy related values from output HTTP headers: those of {@code Authorization} and 56 * {@code Proxy-Authorization}, but for their scheme, so that the output still tells which kind of authentication 57 * was used, and those of {@code Cookie} and {@code Set-Cookie}. 58 * @param headers Unmodified headers, with a single value or a list of values for each 59 * @return Stripped copy of the headers, in the same order (privacy related issues removed) 60 * @since xxx 61 */ 62 public static Map<String, Object> stripHeaders(Map<String, ?> headers) { 63 final Map<String, Object> stripped = new LinkedHashMap<>(headers); 64 stripped.replaceAll((key, value) -> { 65 final String name = key == null ? "" : key.toLowerCase(Locale.ROOT); 66 if ("authorization".equals(name) || "proxy-authorization".equals(name)) { 67 return stripHeaderValue(value, true); 68 } else if ("cookie".equals(name) || "set-cookie".equals(name)) { 69 return stripHeaderValue(value, false); 70 } 71 return value; 72 }); 73 return stripped; 74 } 75 76 private static Object stripHeaderValue(Object value, boolean keepScheme) { 77 if (value instanceof List) { 78 return ((List<?>) value).stream().map(v -> stripHeaderValue(v, keepScheme)).collect(Collectors.toList()); 79 } 80 final String text = String.valueOf(value); 81 final int space = text.indexOf(' '); 82 return (keepScheme && space > 0 ? text.substring(0, space + 1) : "") + STRIPPED; 32 83 } 33 84 34 85 } -
new file test/unit/org/openstreetmap/josm/actions/ShowStatusReportActionTest.java
diff --git test/unit/org/openstreetmap/josm/actions/ShowStatusReportActionTest.java test/unit/org/openstreetmap/josm/actions/ShowStatusReportActionTest.java new file mode 100644 index 0000000000..60c15da87d
- + 1 // License: GPL. For details, see LICENSE file. 2 package org.openstreetmap.josm.actions; 3 4 import static org.junit.jupiter.api.Assertions.assertEquals; 5 6 import java.util.Arrays; 7 import java.util.Collections; 8 import java.util.LinkedHashMap; 9 import java.util.Map; 10 11 import org.junit.jupiter.api.Test; 12 import org.openstreetmap.josm.testutils.annotations.BasicPreferences; 13 14 /** 15 * Unit tests of {@link ShowStatusReportAction}. 16 */ 17 @BasicPreferences 18 class ShowStatusReportActionTest { 19 /** 20 * The API keys and tokens in the URLs of preference values, e.g. of custom imagery, are stripped from the status 21 * report; other values are kept. 22 */ 23 @Test 24 void testValueCleanupStripsUrls() { 25 assertEquals("https://tiles.example.org/{zoom}/{x}/{y}.png?apikey=...stripped...", 26 ShowStatusReportAction.valueCleanup("https://tiles.example.org/{zoom}/{x}/{y}.png?apikey=a-secret-key")); 27 28 final Map<String, String> imagery = new LinkedHashMap<>(); 29 imagery.put("name", "Custom"); 30 imagery.put("url", "https://tiles.example.org/{zoom}/{x}/{y}.png?access_token=a-secret-token"); 31 assertEquals("[{name=Custom, url=https://tiles.example.org/{zoom}/{x}/{y}.png?access_token=...stripped...}]", 32 ShowStatusReportAction.valueCleanup(Collections.singletonList(imagery))); 33 34 assertEquals("[[https://example.org/?key=...stripped..., other]]", ShowStatusReportAction.valueCleanup( 35 Collections.singletonList(Arrays.asList("https://example.org/?key=a-secret-key", "other")))); 36 assertEquals("[a, b]", ShowStatusReportAction.valueCleanup(Arrays.asList("a", "b"))); 37 } 38 } -
test/unit/org/openstreetmap/josm/io/remotecontrol/RemoteControlTest.java
diff --git test/unit/org/openstreetmap/josm/io/remotecontrol/RemoteControlTest.java test/unit/org/openstreetmap/josm/io/remotecontrol/RemoteControlTest.java index 304ff15206..141561f1a7 100644
2 2 package org.openstreetmap.josm.io.remotecontrol; 3 3 4 4 import static org.junit.jupiter.api.Assertions.assertEquals; 5 import static org.junit.jupiter.api.Assertions.assertFalse; 6 import static org.junit.jupiter.api.Assertions.assertTrue; 5 7 6 8 import java.io.IOException; 7 9 import java.io.InputStream; … … import java.net.HttpURLConnection; 9 11 import java.net.URL; 10 12 import java.nio.charset.StandardCharsets; 11 13 import java.security.GeneralSecurityException; 14 import java.util.ArrayList; 15 import java.util.Collections; 16 import java.util.List; 17 import java.util.logging.Handler; 18 import java.util.logging.LogRecord; 12 19 13 20 import org.junit.jupiter.api.AfterEach; 14 21 import org.junit.jupiter.api.BeforeEach; … … import org.junit.jupiter.api.Test; 16 23 import org.openstreetmap.josm.spi.preferences.Config; 17 24 import org.openstreetmap.josm.testutils.annotations.AssertionsInEDT; 18 25 import org.openstreetmap.josm.testutils.annotations.HTTPS; 26 import org.openstreetmap.josm.tools.Logging; 19 27 20 28 /** 21 29 * Unit tests for Remote Control … … class RemoteControlTest { 53 61 testListOfCommands(httpBase); 54 62 } 55 63 64 /** 65 * The OAuth 2.0 authorization code of the redirect to Remote Control is not written to the log. 66 * @throws Exception if an error occurs 67 */ 68 @Test 69 void testAuthorizationCodeIsNotLogged() throws Exception { 70 final List<String> logged = Collections.synchronizedList(new ArrayList<>()); 71 final Handler handler = new Handler() { 72 @Override 73 public void publish(LogRecord logRecord) { 74 logged.add(String.valueOf(logRecord.getMessage())); 75 } 76 77 @Override 78 public void flush() { 79 // nothing to flush 80 } 81 82 @Override 83 public void close() { 84 // nothing to close 85 } 86 }; 87 Logging.getLogger().addHandler(handler); 88 try { 89 HttpURLConnection connection = (HttpURLConnection) new URL(httpBase 90 + "/oauth_authorization?code=a-secret-code&state=a-state").openConnection(); 91 connection.connect(); 92 connection.getResponseCode(); 93 connection.disconnect(); 94 } finally { 95 Logging.getLogger().removeHandler(handler); 96 } 97 final String log = String.join("\n", logged); 98 assertTrue(log.contains("RemoteControl received: GET /oauth_authorization?code=...stripped...&state=a-state"), log); 99 assertFalse(log.contains("a-secret-code"), log); 100 } 101 56 102 private void testListOfCommands(String url) throws IOException, ReflectiveOperationException { 57 103 HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); 58 104 connection.connect(); -
new file test/unit/org/openstreetmap/josm/tools/HttpClientCredentialsLoggingTest.java
diff --git test/unit/org/openstreetmap/josm/tools/HttpClientCredentialsLoggingTest.java test/unit/org/openstreetmap/josm/tools/HttpClientCredentialsLoggingTest.java new file mode 100644 index 0000000000..1d1feb67c4
- + 1 // License: GPL. For details, see LICENSE file. 2 package org.openstreetmap.josm.tools; 3 4 import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; 5 import static com.github.tomakehurst.wiremock.client.WireMock.get; 6 import static com.github.tomakehurst.wiremock.client.WireMock.post; 7 import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; 8 import static org.junit.jupiter.api.Assertions.assertFalse; 9 import static org.junit.jupiter.api.Assertions.assertTrue; 10 11 import java.net.URI; 12 import java.nio.charset.StandardCharsets; 13 import java.util.ArrayList; 14 import java.util.Collections; 15 import java.util.List; 16 import java.util.logging.Handler; 17 import java.util.logging.Level; 18 import java.util.logging.LogRecord; 19 import java.util.logging.SimpleFormatter; 20 21 import org.junit.jupiter.api.AfterEach; 22 import org.junit.jupiter.api.BeforeEach; 23 import org.junit.jupiter.api.Test; 24 import org.openstreetmap.josm.testutils.annotations.BasicPreferences; 25 import org.openstreetmap.josm.testutils.annotations.BasicWiremock; 26 import org.openstreetmap.josm.testutils.annotations.HTTP; 27 28 import com.github.tomakehurst.wiremock.junit5.WireMockRuntimeInfo; 29 30 /** 31 * Credentials are not written to the log by {@link HttpClient}: debug and trace logs are often posted in public 32 * tickets. The stripping itself is tested in {@link TextUtilsTest}. 33 */ 34 @BasicPreferences 35 @BasicWiremock 36 @HTTP 37 class HttpClientCredentialsLoggingTest { 38 private static final String TOKEN = "a-secret-bearer-token"; 39 private static final String COOKIE = "a-secret-session-cookie"; 40 private static final String CLIENT_SECRET = "a-secret-client-secret"; 41 42 private final List<String> logged = Collections.synchronizedList(new ArrayList<>()); 43 private final SimpleFormatter formatter = new SimpleFormatter(); 44 private final Handler handler = new Handler() { 45 @Override 46 public void publish(LogRecord logRecord) { 47 logged.add(formatter.formatMessage(logRecord)); 48 } 49 50 @Override 51 public void flush() { 52 // nothing to flush 53 } 54 55 @Override 56 public void close() { 57 // nothing to close 58 } 59 }; 60 private Level level; 61 62 @BeforeEach 63 void setUp() { 64 level = Logging.getLogger().getLevel(); 65 Logging.getLogger().addHandler(handler); 66 Logging.setLogLevel(Logging.LEVEL_TRACE); 67 } 68 69 @AfterEach 70 void tearDown() { 71 Logging.getLogger().removeHandler(handler); 72 Logging.setLogLevel(level); 73 } 74 75 /** 76 * A request with a bearer token, answered with a session cookie, and a token request with a client secret, are 77 * logged at trace level without any of them. 78 * @param wireMock the server answering the requests 79 * @throws Exception if a request fails 80 */ 81 @Test 82 void testRequestsAreLoggedWithoutCredentials(WireMockRuntimeInfo wireMock) throws Exception { 83 wireMock.getWireMock().register(get(urlEqualTo("/api/0.6/user/details")) 84 .willReturn(aResponse().withStatus(200).withHeader("Set-Cookie", "_osm_session=" + COOKIE).withBody("<osm/>"))); 85 wireMock.getWireMock().register(post(urlEqualTo("/oauth2/token")) 86 .willReturn(aResponse().withStatus(200).withBody("{}"))); 87 88 final HttpClient details = HttpClient.create(URI.create(wireMock.getHttpBaseUrl() + "/api/0.6/user/details").toURL()); 89 details.setHeader("Authorization", "Bearer " + TOKEN); 90 try { 91 details.connect(); 92 } finally { 93 details.disconnect(); 94 } 95 final HttpClient token = HttpClient.create(URI.create(wireMock.getHttpBaseUrl() + "/oauth2/token").toURL(), "POST"); 96 token.setHeader("Content-Type", "application/x-www-form-urlencoded"); 97 token.setRequestBody(("grant_type=authorization_code&client_id=an-id&client_secret=" + CLIENT_SECRET + "&code=a-code") 98 .getBytes(StandardCharsets.UTF_8)); 99 try { 100 token.connect(); 101 } finally { 102 token.disconnect(); 103 } 104 105 final String log = String.join("\n", logged); 106 assertTrue(log.contains("Authorization=Bearer ...stripped..."), log); 107 assertTrue(log.contains("client_secret=...stripped..."), log); 108 for (String secret : new String[] {TOKEN, COOKIE, CLIENT_SECRET}) { 109 assertFalse(log.contains(secret), () -> "logged: " + secret + "\n" + log); 110 } 111 } 112 } -
new file test/unit/org/openstreetmap/josm/tools/TextUtilsTest.java
diff --git test/unit/org/openstreetmap/josm/tools/TextUtilsTest.java test/unit/org/openstreetmap/josm/tools/TextUtilsTest.java new file mode 100644 index 0000000000..96841967d6
- + 1 // License: GPL. For details, see LICENSE file. 2 package org.openstreetmap.josm.tools; 3 4 import static org.junit.jupiter.api.Assertions.assertEquals; 5 6 import java.util.Arrays; 7 import java.util.Collections; 8 import java.util.LinkedHashMap; 9 import java.util.List; 10 import java.util.Map; 11 import java.util.TreeMap; 12 13 import org.junit.jupiter.api.Test; 14 15 /** 16 * Unit tests of {@link TextUtils}. 17 */ 18 class TextUtilsTest { 19 20 /** 21 * Test of {@link TextUtils#wrapLongUrl}. 22 */ 23 @Test 24 void testWrapLongUrl() { 25 assertEquals("https://example.org/x?a=1&b=2", TextUtils.wrapLongUrl("https://example.org/x?a=1&b=2")); 26 } 27 28 /** 29 * API keys and tokens in a URL are stripped, as before; other parameters are kept. 30 */ 31 @Test 32 void testStripUrl() { 33 assertEquals("https://example.org/{z}/{x}/{y}.png?access_token=...stripped...&style=dark", 34 TextUtils.stripUrl("https://example.org/{z}/{x}/{y}.png?access_token=abc&style=dark")); 35 assertEquals("https://example.org/tiles?apikey=...stripped...&connectId=...stripped...", 36 TextUtils.stripUrl("https://example.org/tiles?apikey=abc&connectId=def")); 37 assertEquals("https://example.org/search?q=Main+Street&postcode=AB1", 38 TextUtils.stripUrl("https://example.org/search?q=Main+Street&postcode=AB1")); 39 } 40 41 /** 42 * The OAuth 2.0 authorization code in the redirect received by Remote Control is stripped. 43 */ 44 @Test 45 void testStripUrlAuthorizationCode() { 46 assertEquals("GET /oauth_authorization?code=...stripped...&state=a-state HTTP/1.1", 47 TextUtils.stripUrl("GET /oauth_authorization?code=a-code&state=a-state HTTP/1.1")); 48 assertEquals("GET /oauth_authorization?state=a-state&code=...stripped... HTTP/1.1", 49 TextUtils.stripUrl("GET /oauth_authorization?state=a-state&code=a-code HTTP/1.1")); 50 } 51 52 /** 53 * The credentials of an OAuth 2.0 token request are stripped from its form-encoded body; the other parameters are 54 * kept, among them the grant type, whose value may be {@code refresh_token}. 55 */ 56 @Test 57 void testStripUrlFormBody() { 58 assertEquals("grant_type=authorization_code&client_id=an-id&client_secret=...stripped...&redirect_uri=http://x" 59 + "&code=...stripped...&code_verifier=...stripped...", 60 TextUtils.stripUrl("grant_type=authorization_code&client_id=an-id&client_secret=a-secret" 61 + "&redirect_uri=http://x&code=a-code&code_verifier=a-verifier")); 62 assertEquals("grant_type=refresh_token&refresh_token=...stripped...", 63 TextUtils.stripUrl("grant_type=refresh_token&refresh_token=a-refresh-token")); 64 assertEquals("username=someone&password=...stripped...", TextUtils.stripUrl("username=someone&password=secret")); 65 } 66 67 /** 68 * The values of the headers which are credentials are stripped, but for the scheme of an authorization; the 69 * other headers are kept as they are, in the same order. 70 */ 71 @Test 72 void testStripHeaders() { 73 final Map<String, String> request = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); 74 request.put("Accept", "application/xml"); 75 request.put("authorization", "Bearer a-token"); 76 request.put("Proxy-Authorization", "Basic dXNlcjpwYXNzd29yZA=="); 77 request.put("Cookie", "a-cookie=1; other=2"); 78 assertEquals("{Accept=application/xml, authorization=Bearer ...stripped..., Cookie=...stripped..., " 79 + "Proxy-Authorization=Basic ...stripped...}", TextUtils.stripHeaders(request).toString()); 80 81 final Map<String, List<String>> response = new LinkedHashMap<>(); 82 response.put(null, Collections.singletonList("HTTP/1.1 200 OK")); 83 response.put("Set-Cookie", Arrays.asList("_osm_session=a-cookie; path=/; HttpOnly", "other=1")); 84 response.put("Content-Type", Collections.singletonList("application/json")); 85 assertEquals("{null=[HTTP/1.1 200 OK], Set-Cookie=[...stripped..., ...stripped...], Content-Type=[application/json]}", 86 TextUtils.stripHeaders(response).toString()); 87 } 88 }
