From 01c1d0f5e34f17a514a1361d84e08744c62f6265 Mon Sep 17 00:00:00 2001 From: rodrigojara-cko Date: Mon, 16 Nov 2026 09:54:53 +0100 Subject: [PATCH 1/2] fix(client): security hardening Security hardening and input validation in the OAuth client and in request logging. --- README.md | 7 +- .../checkout/ApacheHttpClientTransport.java | 111 +++- src/main/java/com/checkout/BaseUri.java | 28 +- .../CheckoutAuthorizationException.java | 25 + .../com/checkout/EnvironmentSubdomain.java | 5 +- .../com/checkout/OAuthSdkCredentials.java | 232 +++++++- .../ApacheHttpClientTransportLoggingTest.java | 210 +++++++ .../com/checkout/CheckoutSdkBaseUriTest.java | 15 +- .../com/checkout/CheckoutSdkBuilderTest.java | 11 +- .../com/checkout/OAuthSdkCredentialsTest.java | 29 +- .../OAuthSdkCredentialsTokenRequestTest.java | 554 ++++++++++++++++++ 11 files changed, 1174 insertions(+), 53 deletions(-) create mode 100644 src/test/java/com/checkout/ApacheHttpClientTransportLoggingTest.java create mode 100644 src/test/java/com/checkout/OAuthSdkCredentialsTokenRequestTest.java diff --git a/README.md b/README.md index 8f15c1efc..1861c1a74 100644 --- a/README.md +++ b/README.md @@ -466,8 +466,11 @@ The SDK creates a client for every module when it is built, so set `checkoutApi` needed for OAuth. Each of the six API settings must be an absolute `http` or `https` URI with an ASCII host written without percent-encoding, an optional port from 1 to 65535 and no user information, and its path must not hold dot segments, encoded separators or encoded control characters; a query or fragment on it is not sent. Set -`oAuthAuthorizationApi` to the absolute `https` token URI of your environment. With `environmentSubdomain`, the hosts of `checkoutApi` and `oAuthAuthorizationApi` must be -domain names (ASCII letters, digits, `-` and `_`), not IP addresses. Request paths are resolved against the base directory (the path +`oAuthAuthorizationApi` to the absolute `https` token URI of your environment, with an ASCII host written without +percent-encoding, no user information and an optional port from 1 to 65535; a local mock server can use `http` on +`localhost`, `127.0.0.0/8` or `[::1]` only, and any other `http` URI throws `CheckoutArgumentException` when the SDK is +built. With `environmentSubdomain`, the hosts of `checkoutApi` and `oAuthAuthorizationApi` must be domain names (ASCII +letters, digits, `-` and `_`), not IP addresses. Request paths are resolved against the base directory (the path up to the last `/`), which is kept: end the URI with `/` when it has a path, otherwise its last segment is replaced. A missing or invalid URI fails `build()` with a `CheckoutArgumentException` that names the setting. diff --git a/src/main/java/com/checkout/ApacheHttpClientTransport.java b/src/main/java/com/checkout/ApacheHttpClientTransport.java index 0ee472b11..c315c68a9 100644 --- a/src/main/java/com/checkout/ApacheHttpClientTransport.java +++ b/src/main/java/com/checkout/ApacheHttpClientTransport.java @@ -30,12 +30,18 @@ import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; +import java.io.ByteArrayOutputStream; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; +import java.nio.charset.StandardCharsets; import java.util.Arrays; +import java.util.Collections; +import java.util.HashSet; import java.util.List; +import java.util.Locale; import java.util.Map; +import java.util.Set; import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Executor; @@ -54,6 +60,10 @@ import static org.apache.http.HttpHeaders.CONTENT_TYPE; import static org.apache.http.HttpHeaders.USER_AGENT; +/** + * The Apache HttpClient transport: builds and sends every API request with the SDK headers, retries and telemetry, + * and logs each request and response. + */ @Slf4j class ApacheHttpClientTransport implements Transport { @@ -63,6 +73,9 @@ class ApacheHttpClientTransport implements Transport { private static final String PURPOSE = "purpose"; private static final String PATH = "path"; private static final String INVALID_REQUEST_PATH = "Invalid request path"; + private static final int MAX_DECODING_ROUNDS = 3; + private static final Set LOGGED_RESPONSE_HEADERS = Collections.unmodifiableSet(new HashSet<>(Arrays.asList( + "cko-request-id", "cko-version", "content-type", "content-length", "date"))); private final URI baseUri; private final String baseDirectory; @@ -227,12 +240,16 @@ private Response performCall(final SdkAuthorization authorization, return performCall(authorization, requestBody, request, clientOperation, null); } + /** + * Sends the request and logs the operation with its path and the response status with the allowlisted response + * headers. + */ private Response performCall(final SdkAuthorization authorization, final Object requestBody, final HttpUriRequest request, final ClientOperation clientOperation, final IHeaders customHeaders) { - log.info("{}: {}", clientOperation, request.getURI()); + log.info("{}: {}", clientOperation, loggablePath(request.getURI().getRawPath())); request.setHeader(USER_AGENT, PROJECT_NAME + "/" + getVersionFromManifest()); request.setHeader(ACCEPT, getAcceptHeader(clientOperation)); request.setHeader(AUTHORIZATION, authorization.getAuthorizationHeader()); @@ -268,7 +285,8 @@ private Response performCall(final SdkAuthorization authorization, try (final CloseableHttpResponse response = httpClient.execute(request)) { long elapsed = System.currentTimeMillis() - startTime; - log.info("Response: " + response.getStatusLine().getStatusCode() + " " + Arrays.toString(response.getAllHeaders())); + log.info("Response: " + response.getStatusLine().getStatusCode() + " " + + escapeForLog(Arrays.toString(loggableResponseHeaders(response.getAllHeaders())))); updateTelemetryData(currentRequestId, elapsed); @@ -341,6 +359,95 @@ private Header[] sanitiseHeaders(final Header[] headers) { .toArray(Header[]::new); } + /** + * The request path written to the log: path segments that hold an at sign, as an email address does ("@", also + * percent-encoded once or more, or its full-width or small form), are masked, and control characters, Unicode + * format characters and line or paragraph separators are percent-encoded. + */ + static String loggablePath(final String rawPath) { + if (rawPath == null || rawPath.isEmpty()) { + return rawPath; + } + final String[] segments = rawPath.split("/", -1); + for (int i = 0; i < segments.length; i++) { + if (holdsAtSign(segments[i])) { + segments[i] = "***"; + } + } + return escapeForLog(String.join("/", segments)); + } + + /** + * Whether the segment, decoded up to {@value #MAX_DECODING_ROUNDS} times, contains an at sign ("@", full-width or + * small form). A segment that still changes after the last decoding is treated as holding one. + */ + private static boolean holdsAtSign(final String segment) { + String value = segment; + for (int round = 0; round <= MAX_DECODING_ROUNDS; round++) { + if (value.indexOf('@') >= 0 || value.indexOf('\uFF20') >= 0 || value.indexOf('\uFE6B') >= 0) { + return true; + } + final String decoded = percentDecode(value); + if (decoded.equals(value)) { + return false; + } + value = decoded; + } + return true; + } + + /** + * Decodes every "%XX" escape as UTF-8 and keeps any other character, malformed escapes included. + */ + private static String percentDecode(final String value) { + final ByteArrayOutputStream bytes = new ByteArrayOutputStream(value.length()); + int i = 0; + while (i < value.length()) { + final boolean escape = value.charAt(i) == '%' && i + 2 < value.length(); + final int high = escape ? Character.digit(value.charAt(i + 1), 16) : -1; + final int low = high >= 0 ? Character.digit(value.charAt(i + 2), 16) : -1; + if (low >= 0) { + bytes.write(high * 16 + low); + i += 3; + } else { + final int codePoint = value.codePointAt(i); + final byte[] encoded = new String(Character.toChars(codePoint)).getBytes(StandardCharsets.UTF_8); + bytes.write(encoded, 0, encoded.length); + i += Character.charCount(codePoint); + } + } + return new String(bytes.toByteArray(), StandardCharsets.UTF_8); + } + + /** + * Percent-encodes the control characters, Unicode format characters and line or paragraph separators of a log + * value; any other character, a space included, is kept. + */ + static String escapeForLog(final String value) { + final StringBuilder escaped = new StringBuilder(value.length()); + value.codePoints().forEach(c -> { + final int type = Character.getType(c); + if (Character.isISOControl(c) || type == Character.FORMAT || type == Character.LINE_SEPARATOR + || type == Character.PARAGRAPH_SEPARATOR) { + for (final byte b : new String(Character.toChars(c)).getBytes(StandardCharsets.UTF_8)) { + escaped.append('%').append(String.format("%02X", b & 0xFF)); + } + } else { + escaped.appendCodePoint(c); + } + }); + return escaped.toString(); + } + + /** + * Response headers written to the log: only the headers of a fixed allowlist. + */ + private static Header[] loggableResponseHeaders(final Header[] headers) { + return Arrays.stream(headers) + .filter(it -> LOGGED_RESPONSE_HEADERS.contains(it.getName().toLowerCase(Locale.ROOT))) + .toArray(Header[]::new); + } + private String getAcceptHeader(final ClientOperation clientOperation) { switch (clientOperation) { case GET: diff --git a/src/main/java/com/checkout/BaseUri.java b/src/main/java/com/checkout/BaseUri.java index 9149a56e7..ad76babef 100644 --- a/src/main/java/com/checkout/BaseUri.java +++ b/src/main/java/com/checkout/BaseUri.java @@ -14,7 +14,8 @@ final class BaseUri { + "and a path without dot segments, encoded separators or encoded control characters"; private static final String INVALID_SUBDOMAIN_URI = "Invalid URI for %s: the environment subdomain can only be " + "added to an absolute URI whose host is a domain name of ASCII letters, digits, \"-\" and \"_\", " - + "written without percent-encoding, not an IP address, with an optional port from 1 to 65535"; + + "written without percent-encoding, not an IP address, with no user information and an optional port " + + "from 1 to 65535"; private static final int MAX_PORT = 65535; private BaseUri() { @@ -57,37 +58,36 @@ static URI normalise(final URI baseUri, final String setting) { } /** - * Prepends the subdomain to the host of the URI, refusing an authority that holds a "%" and a host - * that is not a domain name (see {@link #isDomainName(String)}). Port, raw path, raw query and raw - * fragment of the given URI are copied without decoding (callers pass {@code checkoutApi} already - * normalised); user information is not copied, as before (base URIs refuse it in - * {@link #normalise(URI, String)} before they get here). + * Prepends the subdomain to the host of the URI, refusing an authority that holds user information or + * a "%" and a host that is not a domain name (see {@link #isDomainName(String)}). Port, raw path, raw + * query and raw fragment of the given URI are copied without decoding (callers pass {@code checkoutApi} + * already normalised). * * @param uri the configured URI * @param subdomain the subdomain, already validated * @param setting the name of the setting the URI comes from, used in errors instead of the value * @return the URI on the subdomain host * @throws CheckoutArgumentException if the URI is missing, not absolute with an authority, its - * authority holds a "%", its port is out of range, or its host is not a - * domain name + * authority holds user information or a "%", its port is out of range, + * or its host is not a domain name */ static URI withSubdomain(final URI uri, final String subdomain, final String setting) { if (uri == null) { throw new CheckoutArgumentException(setting + " cannot be null"); } final String authority = uri.getRawAuthority(); - if (uri.getScheme() == null || uri.isOpaque() || authority == null || authority.indexOf('%') >= 0) { + if (uri.getScheme() == null || uri.isOpaque() || authority == null || authority.indexOf('@') >= 0 + || authority.indexOf('%') >= 0) { throw invalid(INVALID_SUBDOMAIN_URI, setting); } - final int hostStart = authority.lastIndexOf('@') + 1; - final String host = hostOf(authority.substring(hostStart)); + final String host = hostOf(authority); if (host == null || !isDomainName(host)) { throw invalid(INVALID_SUBDOMAIN_URI, setting); } final StringBuilder rebuilt = new StringBuilder() .append(uri.getScheme()).append("://") .append(subdomain).append('.') - .append(authority.substring(hostStart)); + .append(authority); if (uri.getRawPath() != null) { rebuilt.append(uri.getRawPath()); } @@ -111,7 +111,7 @@ static URI withSubdomain(final URI uri, final String subdomain, final String set * @return the host (an IPv6 literal keeps its brackets), or null when the host is empty or the port * is not a number from 1 to 65535 (leading zeros allowed); an empty port after ":" is allowed */ - private static String hostOf(final String hostAndPort) { + static String hostOf(final String hostAndPort) { final int hostEnd = hostAndPort.startsWith("[") ? hostAndPort.indexOf(']') + 1 : hostAndPort.indexOf(':'); final String host = hostEnd < 0 ? hostAndPort : hostAndPort.substring(0, hostEnd); final String port = hostEnd < 0 ? "" : hostAndPort.substring(hostEnd); @@ -159,7 +159,7 @@ private static boolean isAsciiLetter(final char c) { return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z'); } - private static boolean isVisibleAscii(final String value) { + static boolean isVisibleAscii(final String value) { for (int i = 0; i < value.length(); i++) { final char c = value.charAt(i); if (c <= ' ' || c > '~') { diff --git a/src/main/java/com/checkout/CheckoutAuthorizationException.java b/src/main/java/com/checkout/CheckoutAuthorizationException.java index f8d789bdc..659b53564 100644 --- a/src/main/java/com/checkout/CheckoutAuthorizationException.java +++ b/src/main/java/com/checkout/CheckoutAuthorizationException.java @@ -2,12 +2,37 @@ import static java.lang.String.format; +/** + * Raised when the credentials cannot authorize a request: the operation needs another authorization type, or the + * OAuth token request fails or returns an invalid token response. + */ public final class CheckoutAuthorizationException extends CheckoutException { + /** + * Creates the exception. + * + * @param message the error message + */ public CheckoutAuthorizationException(final String message) { super(message); } + /** + * Creates the exception with the failure that caused it. + * + * @param message the error message + * @param cause the underlying failure, for example the I/O error of the token request + */ + public CheckoutAuthorizationException(final String message, final Throwable cause) { + super(message, cause); + } + + /** + * The exception for an operation that needs an authorization type the credentials do not provide. + * + * @param authorizationType the authorization type the operation needs + * @return the exception + */ public static CheckoutAuthorizationException invalidAuthorization(final SdkAuthorizationType authorizationType) { return new CheckoutAuthorizationException(format("Operation requires %s authorization type", authorizationType)); } diff --git a/src/main/java/com/checkout/EnvironmentSubdomain.java b/src/main/java/com/checkout/EnvironmentSubdomain.java index 84545c4a1..6b9599aa3 100644 --- a/src/main/java/com/checkout/EnvironmentSubdomain.java +++ b/src/main/java/com/checkout/EnvironmentSubdomain.java @@ -19,11 +19,12 @@ public final class EnvironmentSubdomain { * Moves the environment's base URIs to the merchant-specific subdomain. {@code checkoutApi} is * validated and normalised first with the same rules as every base URI; the rebuilt URIs keep the port, * path, query and fragment of that URI (normalised for {@code checkoutApi}, as configured for - * {@code oAuthAuthorizationApi}) without decoding, and leave out any user information. + * {@code oAuthAuthorizationApi}) without decoding. A URI with user information is refused. * * @param environment the environment whose {@code checkoutApi} and {@code oAuthAuthorizationApi} are moved * @param subdomain the merchant-specific subdomain, typically the client ID without the "cli_" prefix - * @throws CheckoutArgumentException if the subdomain is invalid, a URI is missing or invalid, or its host + * @throws CheckoutArgumentException if the subdomain is invalid, a URI is missing or invalid (user + * information included), or its host * cannot take a subdomain (empty, an IPv6 literal or an IPv4 address); * the error names the setting, never the value */ diff --git a/src/main/java/com/checkout/OAuthSdkCredentials.java b/src/main/java/com/checkout/OAuthSdkCredentials.java index bbd731655..4760f60d6 100644 --- a/src/main/java/com/checkout/OAuthSdkCredentials.java +++ b/src/main/java/com/checkout/OAuthSdkCredentials.java @@ -1,13 +1,20 @@ package com.checkout; +import com.google.gson.JsonParseException; import com.google.gson.annotations.SerializedName; import lombok.extern.slf4j.Slf4j; import org.apache.commons.codec.Charsets; import org.apache.http.HttpHeaders; +import org.apache.http.HttpStatus; import org.apache.http.NameValuePair; +import org.apache.http.ParseException; +import org.apache.http.client.ClientProtocolException; +import org.apache.http.client.config.RequestConfig; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.Configurable; import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.utils.URIUtils; import org.apache.http.entity.ContentType; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; @@ -17,7 +24,11 @@ import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URI; +import java.time.DateTimeException; +import java.time.LocalDateTime; import java.util.Arrays; +import java.util.Collections; +import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.stream.Collectors; @@ -26,9 +37,25 @@ import static java.lang.String.format; import static java.time.LocalDateTime.now; +/** + * OAuth client credentials: requests an access token from the authorization URI with the client id, secret and + * scopes, caches it and renews it when it expires. + */ @Slf4j final class OAuthSdkCredentials extends SdkCredentials { + private static final String INVALID_AUTHORIZATION_URI = "OAuth authorization URI must be an absolute https URI"; + private static final String TOKEN_REQUEST_FAILED = "OAuth token request failed with status "; + private static final String INVALID_TOKEN_RESPONSE = "OAuth token response is invalid"; + private static final String AUTHENTICATION_FAILED_WITH_ERROR = "OAuth client_credentials authentication failed with error: %s"; + + /** + * The error codes of RFC 6749 section 5.2. + */ + private static final Set OAUTH_ERROR_CODES = Collections.unmodifiableSet(new HashSet<>(Arrays.asList( + "invalid_request", "invalid_client", "invalid_grant", "unauthorized_client", "unsupported_grant_type", + "invalid_scope"))); + private final URI authorizationUri; private final String clientId; private final String clientSecret; @@ -39,6 +66,16 @@ final class OAuthSdkCredentials extends SdkCredentials { private OAuthAccessToken accessToken; + /** + * Creates the credentials. No token is requested until {@link #initOAuthAccess()} or the first request. + * + * @param httpClientBuilder the builder of the client that sends the token requests + * @param authorizationUri the OAuth token endpoint: an absolute https URI, or http to a loopback host + * @param clientId the OAuth client id + * @param clientSecret the OAuth client secret + * @param scopes the scopes requested + * @throws CheckoutArgumentException if a parameter is null or the authorization URI is not accepted + */ OAuthSdkCredentials(final HttpClientBuilder httpClientBuilder, final URI authorizationUri, final String clientId, @@ -47,18 +84,32 @@ final class OAuthSdkCredentials extends SdkCredentials { super(PlatformType.DEFAULT_OAUTH); validateParams("httpClientBuilder", httpClientBuilder, "authorizationUri", authorizationUri, "clientId", clientId, "clientSecret", clientSecret, "scopes", scopes); + this.authorizationUri = validateAuthorizationUri(authorizationUri); this.client = httpClientBuilder.build(); - this.authorizationUri = authorizationUri; this.clientId = clientId; this.clientSecret = clientSecret; this.scopes = scopes; this.serializer = new GsonSerializer(); } + /** + * Requests the first access token, so a configuration error shows when the SDK is built. + * + * @throws CheckoutAuthorizationException if the token request fails or the token response is invalid + */ void initOAuthAccess() { getAccessToken(); } + /** + * Returns the OAuth authorization for an operation that accepts OAuth, requesting a new token when the cached one + * has expired. + * + * @param authorizationType the authorization type the operation needs + * @return the authorization with the access token + * @throws CheckoutAuthorizationException if the operation does not accept OAuth, the token request fails or the + * token response is invalid + */ @Override public SdkAuthorization getAuthorization(final SdkAuthorizationType authorizationType) { switch (authorizationType) { @@ -71,12 +122,19 @@ public SdkAuthorization getAuthorization(final SdkAuthorizationType authorizatio } } + /** + * Returns the cached token while it is valid, otherwise requests a new one. + * + * @return the access token + * @throws CheckoutAuthorizationException if the token request fails or the token response is invalid + */ private synchronized OAuthAccessToken getAccessToken() { if (accessToken != null && accessToken.isValid()) { log.debug("Using cached OAuth token"); return accessToken; } final HttpPost httpPost = new HttpPost(authorizationUri); + httpPost.setConfig(withoutRedirects(client)); httpPost.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED.getMimeType()); try { final List data = Arrays.asList( @@ -90,62 +148,214 @@ private synchronized OAuthAccessToken getAccessToken() { } log.debug("requesting OAuth token using client_credentials flow"); try (final CloseableHttpResponse response = client.execute(httpPost)) { - final String json = EntityUtils.toString(response.getEntity(), Charsets.UTF_8); - final OAuthServiceResponse oAuthServiceResponse = serializer.fromJson(json, OAuthServiceResponse.class); - if (oAuthServiceResponse == null) { - throw new CheckoutException(format("Invalid OAuth response: %s", json)); + final int statusCode = response.getStatusLine().getStatusCode(); + final String json = readBody(response); + final OAuthServiceResponse oAuthServiceResponse = parseResponse(json); + + if (oAuthServiceResponse != null && isOAuthErrorCode(oAuthServiceResponse.error)) { + throw new CheckoutAuthorizationException(format(AUTHENTICATION_FAILED_WITH_ERROR, oAuthServiceResponse.error)); } - if (oAuthServiceResponse.error != null) { - throw new CheckoutException(format("OAuth client_credentials authentication failed with error: %s", oAuthServiceResponse.error)); + if (statusCode != HttpStatus.SC_OK) { + throw new CheckoutAuthorizationException(TOKEN_REQUEST_FAILED + statusCode); } - if (oAuthServiceResponse.accessToken == null) { - throw new CheckoutException(format("Invalid OAuth response: %s", json)); + final LocalDateTime expirationDate = oAuthServiceResponse == null ? null + : expirationDate(oAuthServiceResponse.expiresIn); + if (oAuthServiceResponse == null + || oAuthServiceResponse.error != null + || oAuthServiceResponse.accessToken == null + || oAuthServiceResponse.accessToken.isEmpty() + || expirationDate == null) { + throw new CheckoutAuthorizationException(INVALID_TOKEN_RESPONSE); } accessToken = new OAuthAccessToken( oAuthServiceResponse.accessToken, oAuthServiceResponse.tokenType, - now().plusSeconds(oAuthServiceResponse.expiresIn) + expirationDate ); log.debug("OAuth token successfully retrieved, expires at: {}", accessToken.getExpirationDate()); return accessToken; + } catch (final ClientProtocolException e) { + throw new CheckoutAuthorizationException(INVALID_TOKEN_RESPONSE); } catch (final IOException e) { - throw new CheckoutException("OAuth client_credentials authentication failed", e); + throw new CheckoutAuthorizationException("OAuth client_credentials authentication failed", e); + } + + } + + /** + * Reads the token endpoint response body. A body that cannot be read or decoded is an invalid token response. + */ + private static String readBody(final CloseableHttpResponse response) { + if (response.getEntity() == null) { + return ""; + } + try { + return EntityUtils.toString(response.getEntity(), Charsets.UTF_8); + } catch (final IOException | ParseException | IllegalArgumentException e) { + throw new CheckoutAuthorizationException(INVALID_TOKEN_RESPONSE); + } + } + + /** + * Parses the token endpoint response. A body that is not a JSON object yields {@code null}. + */ + private OAuthServiceResponse parseResponse(final String json) { + try { + return serializer.fromJson(json, OAuthServiceResponse.class); + } catch (final JsonParseException e) { + return null; + } + } + + /** + * Whether the value is one of the error codes of RFC 6749 section 5.2. + */ + private static boolean isOAuthErrorCode(final String error) { + return error != null && OAUTH_ERROR_CODES.contains(error); + } + + /** + * The expiration date of a token that lasts {@code expiresIn} seconds from now, or {@code null} when the value + * is missing, not positive or too large for a date. + */ + private static LocalDateTime expirationDate(final Long expiresIn) { + if (expiresIn == null || expiresIn <= 0) { + return null; + } + try { + return now().plusSeconds(expiresIn); + } catch (final DateTimeException | ArithmeticException e) { + return null; + } + } + + /** + * The request configuration of the client with redirects turned off, so the token request is sent only to the + * checked authorization URI. A request configuration replaces the client one, so the client one is copied. + */ + private static RequestConfig withoutRedirects(final CloseableHttpClient client) { + final RequestConfig clientConfig = client instanceof Configurable ? ((Configurable) client).getConfig() : null; + return RequestConfig.copy(clientConfig == null ? RequestConfig.DEFAULT : clientConfig) + .setRedirectsEnabled(false) + .build(); + } + + /** + * The token endpoint must be an absolute https URI; http is accepted for loopback hosts only (localhost, + * 127.0.0.0/8 and ::1), for local mock servers. As for the base URIs, the authority holds visible ASCII + * characters only, no user information and no "%", and an optional port from 1 to 65535. + * + * @param authorizationUri the OAuth token endpoint + * @return the same URI + * @throws CheckoutArgumentException if the URI is not https, or http to a host other than loopback, or its + * authority holds a character that is not visible ASCII, user + * information, a "%" or a port out of range + */ + static URI validateAuthorizationUri(final URI authorizationUri) { + final String scheme = authorizationUri.getScheme(); + final String authority = authorizationUri.getRawAuthority(); + if (authorizationUri.isAbsolute() && !authorizationUri.isOpaque() && scheme != null && authority != null + && authority.indexOf('@') < 0 && authority.indexOf('%') < 0 && BaseUri.isVisibleAscii(authority) + && BaseUri.hostOf(authority) != null) { + if ("https".equalsIgnoreCase(scheme) && URIUtils.extractHost(authorizationUri) != null) { + return authorizationUri; + } + final String host = authorizationUri.getHost(); + if ("http".equalsIgnoreCase(scheme) && host != null && isLoopbackHost(host)) { + return authorizationUri; + } } + throw new CheckoutArgumentException(INVALID_AUTHORIZATION_URI); + } + /** + * Whether the host is localhost (any case), [::1] or an IPv4 address in 127.0.0.0/8 written in canonical form. + */ + private static boolean isLoopbackHost(final String host) { + if ("localhost".equalsIgnoreCase(host) || "[::1]".equals(host)) { + return true; + } + final String[] parts = host.split("\\.", -1); + if (parts.length != 4 || !"127".equals(parts[0])) { + return false; + } + for (final String part : parts) { + if (!part.matches("0|[1-9][0-9]{0,2}") || Integer.parseInt(part) > 255) { + return false; + } + } + return true; } + /** + * Replaces the cached access token (tests). + * + * @param accessToken the token to cache + */ synchronized void setAccessToken(final OAuthAccessToken accessToken) { this.accessToken = accessToken; } + /** + * Replaces the client that sends the token requests (tests). + * + * @param client the client + */ void setClient(final CloseableHttpClient client) { this.client = client; } + /** + * Replaces the serializer of the token responses (tests). + * + * @param serializer the serializer + */ void setSerializer(final GsonSerializer serializer) { this.serializer = serializer; } + /** + * The cached access token, or {@code null} before the first token request. + * + * @return the cached token + */ OAuthAccessToken getOAuthAccessToken() { return accessToken; } + /** + * The token endpoint response ({@code POST /connect/token}). + */ private static class OAuthServiceResponse { + /** + * The access token. [Optional] + */ @SerializedName("access_token") String accessToken; + /** + * The token type. [Optional] + */ @SerializedName("token_type") String tokenType; + /** + * The token lifetime in seconds. [Optional] + */ @SerializedName("expires_in") Long expiresIn; + /** + * The OAuth error code of a failed request. [Optional] + * Enum: "invalid_request" "invalid_client" "invalid_grant" "unauthorized_client" "unsupported_grant_type" + * "invalid_scope" + */ String error; } diff --git a/src/test/java/com/checkout/ApacheHttpClientTransportLoggingTest.java b/src/test/java/com/checkout/ApacheHttpClientTransportLoggingTest.java new file mode 100644 index 000000000..f05202fe9 --- /dev/null +++ b/src/test/java/com/checkout/ApacheHttpClientTransportLoggingTest.java @@ -0,0 +1,210 @@ +package com.checkout; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.net.ServerSocket; +import java.net.Socket; +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Locale; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +import org.apache.http.impl.client.HttpClientBuilder; +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.core.LogEvent; +import org.apache.logging.log4j.core.Logger; +import org.apache.logging.log4j.core.appender.AbstractAppender; +import org.apache.logging.log4j.core.config.Property; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import com.sun.net.httpserver.HttpServer; + +class ApacheHttpClientTransportLoggingTest { + + private static final String QUERY_VALUE = "jane.doe%40example.com"; + private static final String COOKIE = "session=ck_hardening_77"; + private static final String UNLISTED_HEADER = "X-Unlisted-Header"; + + private final SdkAuthorization authorization = new SdkAuthorization(PlatformType.DEFAULT, "sk_test"); + private final List messages = Collections.synchronizedList(new ArrayList<>()); + private final ExecutorService executor = Executors.newSingleThreadExecutor(); + + private HttpServer server; + private Logger transportLogger; + private AbstractAppender appender; + + @BeforeEach + void setUp() throws IOException { + server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); + server.createContext("/", exchange -> { + final byte[] body = "{}".getBytes(StandardCharsets.UTF_8); + exchange.getResponseHeaders().add("Content-Type", "application/json"); + exchange.getResponseHeaders().add("Cko-Request-Id", "req_hardening_1"); + exchange.getResponseHeaders().add("Cko-Version", "1.0.0"); + exchange.getResponseHeaders().add("Set-Cookie", COOKIE); + exchange.getResponseHeaders().add(UNLISTED_HEADER, "unlisted-value"); + exchange.sendResponseHeaders(200, body.length); + try (OutputStream out = exchange.getResponseBody()) { + out.write(body); + } + }); + server.start(); + + appender = new AbstractAppender("capture", null, null, true, Property.EMPTY_ARRAY) { + @Override + public void append(final LogEvent event) { + messages.add(event.getMessage().getFormattedMessage()); + } + }; + appender.start(); + transportLogger = (Logger) LogManager.getLogger(ApacheHttpClientTransport.class); + transportLogger.addAppender(appender); + } + + @AfterEach + void tearDown() { + transportLogger.removeAppender(appender); + appender.stop(); + server.stop(0); + executor.shutdownNow(); + } + + private ApacheHttpClientTransport transport() { + return new ApacheHttpClientTransport(URI.create("http://127.0.0.1:" + server.getAddress().getPort() + "/"), + "checkoutApi", HttpClientBuilder.create(), executor, new DefaultTransportConfiguration(), mock(CheckoutConfiguration.class)); + } + + private String allMessages() { + return String.join("\n", messages); + } + + @Test + void shouldLogTheRequestPathWithoutTheQueryParameters() { + final Response response = transport().invokeSync(ClientOperation.QUERY, "payments", authorization, null, null, + Collections.singletonMap("reference", "jane.doe@example.com")); + + assertEquals(200, response.getStatusCode()); + assertTrue(messages.contains("QUERY: /payments"), allMessages()); + assertFalse(allMessages().contains("jane.doe"), allMessages()); + assertFalse(allMessages().contains("reference="), allMessages()); + } + + @Test + void shouldLogTheRequestPathWithoutAQueryBuiltIntoThePath() { + transport().invokeSync(ClientOperation.GET, "payments?reference=" + QUERY_VALUE, authorization, null, null, null); + + assertTrue(messages.contains("GET: /payments"), allMessages()); + assertFalse(allMessages().contains(QUERY_VALUE), allMessages()); + } + + @Test + void shouldMaskAnEmailAddressInTheLoggedPath() { + transport().invokeSync(ClientOperation.GET, "customers/jane.doe%40example.com", authorization, null, null, null); + + assertTrue(messages.contains("GET: /customers/***"), allMessages()); + assertFalse(allMessages().contains("jane.doe"), allMessages()); + } + + @Test + void shouldFormatTheLoggedPath() { + assertEquals("/customers/***", ApacheHttpClientTransport.loggablePath("/customers/jane.doe%40example.com")); + assertEquals("/customers/***", ApacheHttpClientTransport.loggablePath("/customers/jane.doe%40EXAMPLE.com")); + assertEquals("/customers/***/x", ApacheHttpClientTransport.loggablePath("/customers/a@b/x")); + assertEquals("/customers/***", ApacheHttpClientTransport.loggablePath("/customers/jane%2540example.com")); + assertEquals("/customers/***", ApacheHttpClientTransport.loggablePath("/customers/jane%252540example.com")); + assertEquals("/customers/***", ApacheHttpClientTransport.loggablePath("/customers/jane%EF%BC%A0example.com")); + assertEquals("/customers/***", ApacheHttpClientTransport.loggablePath("/customers/jane\uff20example.com")); + assertEquals("/customers/***", ApacheHttpClientTransport.loggablePath("/customers/jane\ufe6bexample.com")); + assertEquals("/customers/***", ApacheHttpClientTransport.loggablePath("/customers/jane%EF%B9%ABexample.com")); + assertEquals("/customers/***", ApacheHttpClientTransport.loggablePath("/customers/jane%25252525252540x")); + assertEquals("/customers/cus_1%25", ApacheHttpClientTransport.loggablePath("/customers/cus_1%25")); + assertEquals("/customers/cus_%zz", ApacheHttpClientTransport.loggablePath("/customers/cus_%zz")); + assertEquals("/payments/pay_1", ApacheHttpClientTransport.loggablePath("/payments/pay_1")); + assertEquals("/a%E2%80%AEb", ApacheHttpClientTransport.loggablePath("/a\u202eb")); + assertEquals("/a%E2%80%A8b%0D%0A", ApacheHttpClientTransport.loggablePath("/a\u2028b\r\n")); + assertEquals("/a%C2%85%00", ApacheHttpClientTransport.loggablePath("/a\u0085\u0000")); + assertEquals("/%0D%0A", ApacheHttpClientTransport.loggablePath("/%0D%0A")); + assertEquals("/caf\u00e9", ApacheHttpClientTransport.loggablePath("/caf\u00e9")); + assertEquals("/a%E2%80%A9b", ApacheHttpClientTransport.loggablePath("/a\u2029b")); + assertEquals("/a\u00a0b", ApacheHttpClientTransport.loggablePath("/a\u00a0b")); + assertEquals("/files/***/x", ApacheHttpClientTransport.loggablePath("/files/release@v2/x")); + assertEquals("/files/f%2525F0%25259F%252598%252580", + ApacheHttpClientTransport.loggablePath("/files/f%2525F0%25259F%252598%252580")); + assertEquals("/files/\uD83D\uDE00", ApacheHttpClientTransport.loggablePath("/files/\uD83D\uDE00")); + assertEquals("/customers/***", ApacheHttpClientTransport.loggablePath("/customers/\uD83D\uDE00%252540x")); + assertEquals("", ApacheHttpClientTransport.loggablePath("")); + assertEquals(null, ApacheHttpClientTransport.loggablePath(null)); + } + + @Test + void shouldEscapeControlAndFormatCharactersInTheLoggedResponseHeaders() throws Exception { + final byte[] value = "req_\u001b[2J\u0007\u0000\u202ex".getBytes(StandardCharsets.UTF_8); + try (ServerSocket socket = new ServerSocket(0, 1, InetAddress.getByName("127.0.0.1"))) { + final Thread thread = new Thread(() -> { + try (Socket client = socket.accept()) { + final InputStream in = client.getInputStream(); + final StringBuilder head = new StringBuilder(); + int read; + while (head.indexOf("\r\n\r\n") < 0 && (read = in.read()) != -1) { + head.append((char) read); + } + final OutputStream out = client.getOutputStream(); + out.write("HTTP/1.1 204 No Content\r\nCko-Request-Id: ".getBytes(StandardCharsets.US_ASCII)); + out.write(value); + out.write("\r\nConnection: close\r\n\r\n".getBytes(StandardCharsets.US_ASCII)); + out.flush(); + } catch (final IOException ignore) { + // the test fails on the client side + } + }); + thread.setDaemon(true); + thread.start(); + new ApacheHttpClientTransport(URI.create("http://127.0.0.1:" + socket.getLocalPort() + "/"), + "checkoutApi", HttpClientBuilder.create(), executor, new DefaultTransportConfiguration(), mock(CheckoutConfiguration.class)) + .invokeSync(ClientOperation.GET, "payments", authorization, null, null, null); + } + + final String responseLine = messages.stream().filter(it -> it.startsWith("Response: ")).findFirst().orElse(""); + assertTrue(responseLine.startsWith("Response: 204 ["), allMessages()); + assertTrue(responseLine.contains("req_%1B[2J%07%00"), responseLine); + responseLine.codePoints().forEach(c -> { + final int type = Character.getType(c); + assertFalse(Character.isISOControl(c) || type == Character.FORMAT, responseLine); + }); + } + + @Test + void shouldLogOnlyAllowlistedResponseHeaders() { + transport().invokeSync(ClientOperation.GET, "payments/pay_1", authorization, null, null, null); + + // com.sun.net.httpserver sends header names as "Cko-request-id", so names are compared in lower case. + final String responseLine = messages.stream().filter(it -> it.startsWith("Response: ")).findFirst().orElse(""); + final String lowerCase = responseLine.toLowerCase(Locale.ROOT); + final String everything = allMessages().toLowerCase(Locale.ROOT); + assertTrue(responseLine.startsWith("Response: 200 ["), allMessages()); + assertTrue(lowerCase.contains("cko-request-id: req_hardening_1"), responseLine); + assertTrue(lowerCase.contains("cko-version: 1.0.0"), responseLine); + assertTrue(lowerCase.contains("content-type: application/json"), responseLine); + assertTrue(lowerCase.contains("content-length: 2"), responseLine); + assertTrue(lowerCase.contains("date: "), responseLine); + assertFalse(everything.contains(COOKIE), allMessages()); + assertFalse(everything.contains("set-cookie"), allMessages()); + assertFalse(everything.contains(UNLISTED_HEADER.toLowerCase(Locale.ROOT)), allMessages()); + assertFalse(everything.contains("unlisted-value"), allMessages()); + } + +} diff --git a/src/test/java/com/checkout/CheckoutSdkBaseUriTest.java b/src/test/java/com/checkout/CheckoutSdkBaseUriTest.java index c00be5dcd..71df36660 100644 --- a/src/test/java/com/checkout/CheckoutSdkBaseUriTest.java +++ b/src/test/java/com/checkout/CheckoutSdkBaseUriTest.java @@ -244,19 +244,10 @@ void shouldAddTheSubdomainToTheAuthorizationUriWithoutDecodingIt() { new EnvironmentSubdomain(environment, "abc123").getOAuthAuthorizationApi().toString()); } - @Test - void shouldLeaveUserInformationOutOfTheAuthorizationUriOnTheSubdomain() { - final CustomEnvironment environment = CustomEnvironment.builder() - .checkoutApi(VALID) - .oAuthAuthorizationApi(URI.create("https://user:pass@access.example:8443/connect/token")) - .build(); - - assertEquals("https://abc123.access.example:8443/connect/token", - new EnvironmentSubdomain(environment, "abc123").getOAuthAuthorizationApi().toString()); - } - @ParameterizedTest - @ValueSource(strings = {"https://[::1]/connect/token", "http://127.0.0.1/connect/token", "https:///connect/token", + @ValueSource(strings = {"https://user:pass@access.example:8443/connect/token", + "https://user@access.example/connect/token", "https://@access.example/connect/token", + "https://[::1]/connect/token", "http://127.0.0.1/connect/token", "https:///connect/token", "connect/token", "mailto:x@example.com", "https://u%3Ap%40access.example/connect/token", "https://access%2Eexample/connect/token", "http://0x7f000001/connect/token", "https://access.example:0/connect/token", "https://access.example:65536/connect/token"}) diff --git a/src/test/java/com/checkout/CheckoutSdkBuilderTest.java b/src/test/java/com/checkout/CheckoutSdkBuilderTest.java index 72af3aae0..38deb2333 100644 --- a/src/test/java/com/checkout/CheckoutSdkBuilderTest.java +++ b/src/test/java/com/checkout/CheckoutSdkBuilderTest.java @@ -2,6 +2,9 @@ import org.junit.jupiter.api.Test; +import java.io.IOException; +import java.net.InetAddress; +import java.net.ServerSocket; import java.net.URI; import java.net.URISyntaxException; @@ -82,9 +85,15 @@ void shouldFailToCreateOAuthSdkWithBothAuthorizationUriAndSubdomain() throws URI @Test void shouldCreateOAuthSdkWithExplicitAuthorizationUriAndLegacyDomain() throws URISyntaxException { + final int closedPort; + try (ServerSocket socket = new ServerSocket(0, 1, InetAddress.getByName("127.0.0.1"))) { + closedPort = socket.getLocalPort(); + } catch (final IOException e) { + throw new IllegalStateException(e); + } try { new CheckoutSdkBuilder().oAuth() - .clientCredentials(new URI("test"), "client_id", "client_secret") + .clientCredentials(new URI("https://127.0.0.1:" + closedPort + "/connect/token"), "client_id", "client_secret") .scopes(OAuthScope.GATEWAY) .environment(Environment.SANDBOX) .useLegacyDomain() diff --git a/src/test/java/com/checkout/OAuthSdkCredentialsTest.java b/src/test/java/com/checkout/OAuthSdkCredentialsTest.java index 595e0b9c6..5e2a9cf7b 100644 --- a/src/test/java/com/checkout/OAuthSdkCredentialsTest.java +++ b/src/test/java/com/checkout/OAuthSdkCredentialsTest.java @@ -1,10 +1,13 @@ package com.checkout; import org.apache.http.HttpEntity; +import org.apache.http.HttpVersion; +import org.apache.http.StatusLine; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; +import org.apache.http.message.BasicStatusLine; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; @@ -37,6 +40,10 @@ class OAuthSdkCredentialsTest { private static final String BEARER = "Bearer "; + private static final URI TOKEN_URI = URI.create("https://test.checkout.com/oauth/token"); + + private static final StatusLine OK = new BasicStatusLine(HttpVersion.HTTP_1_1, 200, "OK"); + @Mock private CloseableHttpClient client; @@ -78,7 +85,7 @@ void shouldFailCreatingDefaultOAuthSdkCredentials() { @Test void shouldCreateOAuthSdkCredentials() { - final SdkCredentials credentials = new OAuthSdkCredentials(DEFAULT_CLIENT_BUILDER, Mockito.mock(URI.class), "client_id", "client_secret", EnumSet.allOf(OAuthScope.class)); + final SdkCredentials credentials = new OAuthSdkCredentials(DEFAULT_CLIENT_BUILDER, TOKEN_URI, "client_id", "client_secret", EnumSet.allOf(OAuthScope.class)); assertEquals(DEFAULT_OAUTH, credentials.getPlatformType()); } @@ -86,7 +93,7 @@ void shouldCreateOAuthSdkCredentials() { @Test void authorization_shouldNotGetWhenTheresAValidAccessToken() { - final OAuthSdkCredentials credentials = new OAuthSdkCredentials(DEFAULT_CLIENT_BUILDER, Mockito.mock(URI.class), "client_id", "client_secret", EnumSet.allOf(OAuthScope.class)); + final OAuthSdkCredentials credentials = new OAuthSdkCredentials(DEFAULT_CLIENT_BUILDER, TOKEN_URI, "client_id", "client_secret", EnumSet.allOf(OAuthScope.class)); credentials.setAccessToken(new OAuthAccessToken("y123", "Bearer", LocalDateTime.now().plusMinutes(5))); credentials.setClient(client); credentials.setSerializer(serializer); @@ -114,6 +121,7 @@ void authorization_shouldGetWhenTheresNoValidAccessToken() throws IOException, U when(entity.getContent()).thenReturn(stream); final CloseableHttpResponse response = Mockito.mock(CloseableHttpResponse.class); + when(response.getStatusLine()).thenReturn(OK); when(response.getEntity()).thenReturn(entity); when(client.execute(Mockito.argThat(req -> req instanceof HttpPost && Objects.equals(req.getURI().toString(), "https://test.checkout.com/oauth/token")))) @@ -154,6 +162,7 @@ void authorization_shouldGetWhenTheresAnExpiredAccessToken() throws IOException, when(entity.getContent()).thenReturn(stream); final CloseableHttpResponse response = Mockito.mock(CloseableHttpResponse.class); + when(response.getStatusLine()).thenReturn(OK); when(response.getEntity()).thenReturn(entity); when(client.execute(any(HttpPost.class))).thenReturn(response); @@ -187,12 +196,13 @@ void shouldThrowExceptionWhenOAuthResponseIsNull() throws IOException { when(entity.getContent()).thenReturn(stream); final CloseableHttpResponse response = Mockito.mock(CloseableHttpResponse.class); + when(response.getStatusLine()).thenReturn(OK); when(response.getEntity()).thenReturn(entity); when(client.execute(any(HttpPost.class))).thenReturn(response); final OAuthSdkCredentials credentials = new OAuthSdkCredentials( DEFAULT_CLIENT_BUILDER, - URI.create("http://test.checkout.com/oauth/token"), + URI.create("https://test.checkout.com/oauth/token"), "client_id", "client_secret", EnumSet.allOf(OAuthScope.class)); @@ -200,11 +210,11 @@ void shouldThrowExceptionWhenOAuthResponseIsNull() throws IOException { credentials.setClient(client); CheckoutException exception = assertThrows( - CheckoutException.class, + CheckoutAuthorizationException.class, () -> credentials.getAuthorization(SdkAuthorizationType.PUBLIC_KEY_OR_OAUTH) ); - assertEquals("Invalid OAuth response: {}", exception.getMessage()); + assertEquals("OAuth token response is invalid", exception.getMessage()); } @Test @@ -218,6 +228,7 @@ void shouldThrowExceptionWhenAccessTokenIsNull() throws IOException { when(entity.getContent()).thenReturn(stream); final CloseableHttpResponse response = Mockito.mock(CloseableHttpResponse.class); + when(response.getStatusLine()).thenReturn(OK); when(response.getEntity()).thenReturn(entity); when(client.execute(any(HttpPost.class))).thenReturn(response); @@ -231,12 +242,11 @@ void shouldThrowExceptionWhenAccessTokenIsNull() throws IOException { credentials.setClient(client); CheckoutException exception = assertThrows( - CheckoutException.class, + CheckoutAuthorizationException.class, () -> credentials.getAuthorization(SdkAuthorizationType.PUBLIC_KEY_OR_OAUTH) ); - assertEquals("Invalid OAuth response: { \"access_token\": null, \"token_type\": \"Bearer\", \"expires_in\": 3600 }", - exception.getMessage()); + assertEquals("OAuth token response is invalid", exception.getMessage()); } @Test @@ -247,6 +257,7 @@ void shouldThrowExceptionWhenOAuthResponseContainsError() throws IOException { when(entity.getContent()).thenReturn(stream); final CloseableHttpResponse response = Mockito.mock(CloseableHttpResponse.class); + when(response.getStatusLine()).thenReturn(OK); when(response.getEntity()).thenReturn(entity); when(client.execute(any(HttpPost.class))).thenReturn(response); @@ -260,7 +271,7 @@ void shouldThrowExceptionWhenOAuthResponseContainsError() throws IOException { credentials.setClient(client); CheckoutException exception = assertThrows( - CheckoutException.class, + CheckoutAuthorizationException.class, () -> credentials.getAuthorization(SdkAuthorizationType.PUBLIC_KEY_OR_OAUTH) ); diff --git a/src/test/java/com/checkout/OAuthSdkCredentialsTokenRequestTest.java b/src/test/java/com/checkout/OAuthSdkCredentialsTokenRequestTest.java new file mode 100644 index 000000000..feb7d9441 --- /dev/null +++ b/src/test/java/com/checkout/OAuthSdkCredentialsTokenRequestTest.java @@ -0,0 +1,554 @@ +package com.checkout; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.net.ServerSocket; +import java.net.Socket; +import java.net.SocketTimeoutException; +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.time.LocalDateTime; +import java.util.EnumSet; +import java.util.concurrent.atomic.AtomicInteger; + +import org.apache.http.client.config.RequestConfig; +import org.apache.http.impl.client.HttpClientBuilder; +import org.apache.http.impl.client.LaxRedirectStrategy; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +import com.sun.net.httpserver.HttpServer; + +class OAuthSdkCredentialsTokenRequestTest { + + private static final String CLIENT_SECRET = "cs_hardening_value_42"; + private static final String ECHO = "{{request}}"; + private static final String TOKEN_REQUEST_FAILED = "OAuth token request failed with status "; + private static final String INVALID_TOKEN_RESPONSE = "OAuth token response is invalid"; + private static final String INVALID_URI = "OAuth authorization URI must be an absolute https URI"; + + private HttpServer server; + private volatile int status; + private volatile String contentType; + private volatile String body; + private volatile String location; + private final AtomicInteger requests = new AtomicInteger(); + private final AtomicInteger targetRequests = new AtomicInteger(); + + @BeforeEach + void startServer() throws IOException { + server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); + server.createContext("/", exchange -> { + requests.incrementAndGet(); + final String request = readAll(exchange.getRequestBody()); + final byte[] response = body.replace(ECHO, request).getBytes(StandardCharsets.UTF_8); + exchange.getResponseHeaders().add("Content-Type", contentType); + if (location != null) { + exchange.getResponseHeaders().add("Location", location); + } + exchange.sendResponseHeaders(status, response.length == 0 ? -1 : response.length); + try (OutputStream out = exchange.getResponseBody()) { + out.write(response); + } + }); + server.start(); + } + + @AfterEach + void stopServer() { + server.stop(0); + } + + private static String readAll(final InputStream in) throws IOException { + final ByteArrayOutputStream out = new ByteArrayOutputStream(); + final byte[] buffer = new byte[1024]; + int read; + while ((read = in.read(buffer)) != -1) { + out.write(buffer, 0, read); + } + return out.toString(StandardCharsets.UTF_8.name()); + } + + private void respond(final int status, final String contentType, final String body) { + this.status = status; + this.contentType = contentType; + this.body = body; + } + + private URI tokenUri() { + return URI.create("http://127.0.0.1:" + server.getAddress().getPort() + "/connect/token"); + } + + private static OAuthSdkCredentials credentials(final URI authorizationUri) { + final RequestConfig timeouts = RequestConfig.custom() + .setConnectTimeout(5000).setConnectionRequestTimeout(5000).setSocketTimeout(5000).build(); + return new OAuthSdkCredentials(HttpClientBuilder.create().setDefaultRequestConfig(timeouts), authorizationUri, + "client_id", CLIENT_SECRET, EnumSet.of(OAuthScope.GATEWAY)); + } + + private static int closedPort() throws IOException { + try (ServerSocket socket = new ServerSocket(0, 1, InetAddress.getByName("127.0.0.1"))) { + return socket.getLocalPort(); + } + } + + private CheckoutException requestFails() { + final OAuthSdkCredentials credentials = credentials(tokenUri()); + return assertThrows(CheckoutException.class, + () -> credentials.getAuthorization(SdkAuthorizationType.OAUTH)); + } + + private static void assertOnlyFixedText(final Throwable thrown) { + for (Throwable t = thrown; t != null; t = t.getCause()) { + final String text = String.valueOf(t.getMessage()) + " " + t; + assertFalse(text.contains(CLIENT_SECRET), "unexpected text in " + t.getClass().getName() + ": " + text); + assertFalse(text.contains(""), "unexpected text in " + t.getClass().getName() + ": " + text); + assertFalse(text.contains("tok_"), "unexpected text in " + t.getClass().getName() + ": " + text); + } + } + + /** + * Answers one request on a raw socket with the given bytes, for responses HttpServer cannot produce. + */ + private static URI rawServer(final ServerSocket socket, final String response) { + final Thread thread = new Thread(() -> { + try (Socket client = socket.accept()) { + final InputStream in = client.getInputStream(); + final StringBuilder head = new StringBuilder(); + int read; + while (head.indexOf("\r\n\r\n") < 0 && (read = in.read()) != -1) { + head.append((char) read); + } + final String lower = head.toString().toLowerCase(); + final int start = lower.indexOf("content-length:"); + final int length = Integer.parseInt(lower.substring(start + 15, lower.indexOf("\r\n", start)).trim()); + for (int i = 0; i < length; i++) { + in.read(); + } + final OutputStream out = client.getOutputStream(); + out.write(response.getBytes(StandardCharsets.US_ASCII)); + out.flush(); + } catch (final IOException ignore) { + // the test fails on the client side + } + }); + thread.setDaemon(true); + thread.start(); + return URI.create("http://127.0.0.1:" + socket.getLocalPort() + "/connect/token"); + } + + private void assertTokenRequestFails(final String expectedMessage) { + final CheckoutException exception = requestFails(); + assertInstanceOf(CheckoutAuthorizationException.class, exception); + assertEquals(expectedMessage, exception.getMessage()); + assertOnlyFixedText(exception); + } + + @Test + void shouldRejectServerErrorWithHtmlBody() { + respond(500, "text/html", "upstream failed for " + ECHO + ""); + + assertTokenRequestFails(TOKEN_REQUEST_FAILED + 500); + } + + @Test + void shouldRejectServerErrorWithJsonBodyWithoutError() { + respond(503, "application/json", "{\"access_token\":\"tok_1\",\"expires_in\":3600,\"echo\":\"" + ECHO + "\"}"); + + assertTokenRequestFails(TOKEN_REQUEST_FAILED + 503); + } + + @ParameterizedTest + @ValueSource(strings = {"invalid_request", "invalid_client", "invalid_grant", "unauthorized_client", + "unsupported_grant_type", "invalid_scope"}) + void shouldKeepTheOAuthErrorCodeMessage(final String code) { + respond(400, "application/json", "{\"error\":\"" + code + "\",\"error_description\":\"" + ECHO + "\"}"); + + assertTokenRequestFails("OAuth client_credentials authentication failed with error: " + code); + } + + @ParameterizedTest + @ValueSource(strings = { + CLIENT_SECRET, + "tok_\\u0000x", + "tok_\\u202ex", + "tok_\\r\\nx", + "INVALID_CLIENT", + "invalid_client " + }) + void shouldUseTheStatusMessageForAnUnknownErrorCode(final String error) { + respond(400, "application/json", "{\"error\":\"" + error + "\"}"); + + assertTokenRequestFails(TOKEN_REQUEST_FAILED + 400); + } + + @Test + void shouldRejectOkResponseWithAnUnknownError() { + respond(200, "application/json", + "{\"error\":\"" + CLIENT_SECRET + "\",\"access_token\":\"tok_1\",\"token_type\":\"Bearer\",\"expires_in\":3600}"); + + assertTokenRequestFails(INVALID_TOKEN_RESPONSE); + } + + @Test + void shouldRaiseAnAuthorizationExceptionWhenTheTokenRequestFails() throws IOException { + final OAuthSdkCredentials credentials = credentials(URI.create("http://127.0.0.1:" + closedPort() + "/connect/token")); + + final CheckoutException exception = assertThrows(CheckoutException.class, + () -> credentials.getAuthorization(SdkAuthorizationType.OAUTH)); + + assertInstanceOf(CheckoutAuthorizationException.class, exception); + assertEquals("OAuth client_credentials authentication failed", exception.getMessage()); + assertInstanceOf(IOException.class, exception.getCause()); + assertOnlyFixedText(exception); + } + + @Test + void shouldRejectTokenResponseWithAnIllegalCharset() { + respond(200, "application/json; charset=\"a b{}\"", "{\"access_token\":\"tok_1\",\"token_type\":\"Bearer\",\"expires_in\":3600}"); + + final CheckoutException exception = requestFails(); + + assertInstanceOf(CheckoutAuthorizationException.class, exception); + assertEquals(INVALID_TOKEN_RESPONSE, exception.getMessage()); + assertNull(exception.getCause()); + assertFalse(exception.getMessage().contains("a b{}")); + } + + @Test + void shouldNotKeepTheBodyReadErrorAsCause() throws IOException { + try (ServerSocket socket = new ServerSocket(0, 1, InetAddress.getByName("127.0.0.1"))) { + final URI uri = rawServer(socket, "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n" + + "Transfer-Encoding: chunked\r\n\r\ntok_in_chunk_header\r\n"); + final OAuthSdkCredentials credentials = credentials(uri); + + final CheckoutException exception = assertThrows(CheckoutException.class, + () -> credentials.getAuthorization(SdkAuthorizationType.OAUTH)); + + assertInstanceOf(CheckoutAuthorizationException.class, exception); + assertEquals(INVALID_TOKEN_RESPONSE, exception.getMessage()); + assertNull(exception.getCause()); + assertOnlyFixedText(exception); + } + } + + @ParameterizedTest + @ValueSource(strings = { + "HTTP/1.1 200 OK\r\ntok_in_header_without_colon\r\n\r\n", + "HTTP/1.1 2tok_0 OK\r\nContent-Length: 0\r\n\r\n" + }) + void shouldNotKeepTheProtocolErrorAsCause(final String response) throws IOException { + try (ServerSocket socket = new ServerSocket(0, 1, InetAddress.getByName("127.0.0.1"))) { + final OAuthSdkCredentials credentials = credentials(rawServer(socket, response)); + + final CheckoutException exception = assertThrows(CheckoutException.class, + () -> credentials.getAuthorization(SdkAuthorizationType.OAUTH)); + + assertInstanceOf(CheckoutAuthorizationException.class, exception); + assertEquals(INVALID_TOKEN_RESPONSE, exception.getMessage()); + assertNull(exception.getCause()); + assertOnlyFixedText(exception); + } + } + + @Test + void shouldRejectNonOkSuccessStatus() { + respond(202, "application/json", "{\"access_token\":\"tok_1\",\"token_type\":\"Bearer\",\"expires_in\":3600}"); + + assertTokenRequestFails(TOKEN_REQUEST_FAILED + 202); + } + + @ParameterizedTest + @ValueSource(strings = { + "" + ECHO + "", + "", + "{}", + "null", + "[]", + "{\"access_token\":null,\"token_type\":\"Bearer\",\"expires_in\":3600,\"echo\":\"" + ECHO + "\"}", + "{\"access_token\":\"\",\"token_type\":\"Bearer\",\"expires_in\":3600}", + "{\"access_token\":\"tok_1\",\"token_type\":\"Bearer\"}", + "{\"access_token\":\"tok_1\",\"token_type\":\"Bearer\",\"expires_in\":null}", + "{\"access_token\":\"tok_1\",\"token_type\":\"Bearer\",\"expires_in\":0}", + "{\"access_token\":\"tok_1\",\"token_type\":\"Bearer\",\"expires_in\":-1}", + "{\"access_token\":\"tok_1\",\"token_type\":\"Bearer\",\"expires_in\":9223372036854775807}", + "{\"access_token\":\"tok_1\",\"token_type\":\"Bearer\",\"expires_in\":\"soon\"}" + }) + void shouldRejectInvalidTokenResponse(final String responseBody) { + respond(200, "application/json", responseBody); + + assertTokenRequestFails(INVALID_TOKEN_RESPONSE); + } + + @ParameterizedTest + @ValueSource(longs = {1, 3600, 31536001, 3153600000L}) + void shouldAcceptAPositiveTokenLifetime(final long expiresIn) { + respond(200, "application/json", + "{\"access_token\":\"tok_1\",\"token_type\":\"Bearer\",\"expires_in\":" + expiresIn + "}"); + + final OAuthSdkCredentials credentials = credentials(tokenUri()); + final LocalDateTime before = LocalDateTime.now(); + final SdkAuthorization authorization = credentials.getAuthorization(SdkAuthorizationType.OAUTH); + + assertEquals("Bearer tok_1", authorization.getAuthorizationHeader()); + assertNotNull(credentials.getOAuthAccessToken()); + assertEquals("tok_1", credentials.getOAuthAccessToken().getToken()); + assertEquals("Bearer", credentials.getOAuthAccessToken().getTokenType()); + assertFalse(credentials.getOAuthAccessToken().getExpirationDate().isBefore(before.plusSeconds(expiresIn))); + } + + /** + * Token values of every shape: when the response is otherwise invalid, the error message is the fixed text and + * carries none of the token. + */ + @ParameterizedTest + @ValueSource(strings = { + "tok_\\u0000x", + "tok_\\u007fx", + "tok_\\u0085x", + "tok_\\u2028x", + "tok_\\u202ex", + "tok_\\uff54\\uff4f\\uff4b", + "tok_\\u00e9", + "tok_\\r\\n x", + "tok_\\tx", + "Bearer tok_\\r\\nx", + "tok_" + }) + void shouldKeepTheFixedMessageForAnyTokenValue(final String token) { + respond(200, "application/json", "{\"access_token\":\"" + token + "\",\"token_type\":\"Bearer\"}"); + + assertTokenRequestFails(INVALID_TOKEN_RESPONSE); + } + + @Test + void shouldKeepTheFixedMessageForAVeryLongToken() { + final StringBuilder token = new StringBuilder("tok_"); + for (int i = 0; i < 100000; i++) { + token.append('a'); + } + respond(200, "application/json", "{\"access_token\":\"" + token + "\",\"expires_in\":0}"); + + assertTokenRequestFails(INVALID_TOKEN_RESPONSE); + } + + @Test + void shouldKeepTheFixedMessageForAnUnexpectedResponseBody() { + respond(200, "application/json", "{\"client_secret\":\"" + CLIENT_SECRET + "\",\"echo\":\"" + ECHO + "\"}"); + + assertTokenRequestFails(INVALID_TOKEN_RESPONSE); + } + + @ParameterizedTest + @ValueSource(strings = { + "http://access.checkout.com/connect/token", + "http://127.0.0.1.example.com/connect/token", + "http://localhost.example.com/connect/token", + "http://127.0.0.1@example.com/connect/token", + "http://0.0.0.0/connect/token", + "http://128.0.0.1/connect/token", + "http://[::2]/connect/token", + "http://[::ffff:127.0.0.1]/connect/token", + "http://127.1/connect/token", + "http://127.0.0.01/connect/token", + "http://127.0.0.256/connect/token", + "http://0x7f.0.0.1/connect/token", + "http://localhost.evil.com/connect/token", + "http://127.0.0.1.nip.io/connect/token", + "file:///etc/connect/token", + "ftp://access.checkout.com/connect/token", + "ws://localhost/connect/token", + "connect/token", + "test", + "//access.checkout.com/connect/token", + "https:/connect/token", + "https:access.checkout.com", + "https://user@/connect/token", + "https://:443/connect/token", + "mailto:ops@example.com", + "https://user:pass@access.checkout.com/connect/token", + "https://user@access.checkout.com/connect/token", + "https://u%3Ap%40access.checkout.com/connect/token", + "http://user@localhost/connect/token", + "https://access.checkout.com:0/connect/token", + "https://access.checkout.com:65536/connect/token", + "http://localhost:99999/connect/token", + "http://127.0.0.1:0/connect/token", + "https://_x_:99999/connect/token", + "https://acce\u0455s.checkout.com/connect/token", + "https://b\u00fccher.example/connect/token", + "http://l\u043ecalhost/connect/token" + }) + void shouldRejectAuthorizationUriThatIsNotHttps(final String uri) { + final CheckoutArgumentException exception = assertThrows(CheckoutArgumentException.class, + () -> credentials(URI.create(uri))); + + assertEquals(INVALID_URI, exception.getMessage()); + } + + @ParameterizedTest + @ValueSource(strings = { + "https://access.checkout.com/connect/token", + "HTTPS://access.checkout.com/connect/token", + "https://proxy.example:8443/oauth/token?tenant=1", + "http://localhost/connect/token", + "http://LocalHost:8080/connect/token", + "http://127.0.0.1/connect/token", + "http://127.10.20.30:9000/connect/token", + "http://[::1]:9000/connect/token", + "https://access.checkout.com:1/connect/token", + "https://access.checkout.com:65535/connect/token" + }) + void shouldAcceptHttpsOrLoopbackAuthorizationUri(final String uri) { + assertDoesNotThrow(() -> credentials(URI.create(uri))); + } + + @Test + @SuppressWarnings("deprecation") + void shouldRejectHttpAuthorizationUriFromCustomEnvironment() { + final AbstractCheckoutSdkBuilder builder = CheckoutSdk.builder() + .oAuth() + .clientCredentials("client_id", CLIENT_SECRET) + .scopes(OAuthScope.GATEWAY) + .environment(CustomEnvironment.builder() + .checkoutApi(URI.create("https://api.example.com/")) + .oAuthAuthorizationApi(URI.create("http://auth.example.com/connect/token")) + .build()) + .useLegacyDomain(); + + final CheckoutArgumentException exception = assertThrows(CheckoutArgumentException.class, builder::build); + + assertEquals(INVALID_URI, exception.getMessage()); + } + + @Test + @SuppressWarnings("deprecation") + void shouldRejectHttpAuthorizationUriFromTheBuilder() { + final AbstractCheckoutSdkBuilder builder = CheckoutSdk.builder() + .oAuth() + .clientCredentials(URI.create("http://auth.example.com/connect/token"), "client_id", CLIENT_SECRET) + .scopes(OAuthScope.GATEWAY) + .environment(Environment.SANDBOX) + .useLegacyDomain(); + + final CheckoutArgumentException exception = assertThrows(CheckoutArgumentException.class, builder::build); + + assertEquals(INVALID_URI, exception.getMessage()); + } + + @ParameterizedTest + @ValueSource(ints = {301, 302, 303, 307, 308}) + void shouldNotFollowARedirectOfTheTokenRequest(final int redirectStatus) throws IOException { + final HttpServer target = tokenServer(); + try { + location = "http://127.0.0.1:" + target.getAddress().getPort() + "/elsewhere"; + respond(redirectStatus, "text/plain", ""); + + final CheckoutException exception = requestFails(); + + assertInstanceOf(CheckoutAuthorizationException.class, exception); + assertEquals(TOKEN_REQUEST_FAILED + redirectStatus, exception.getMessage()); + assertOnlyFixedText(exception); + assertEquals(0, targetRequests.get()); + } finally { + target.stop(0); + } + } + + @ParameterizedTest + @ValueSource(ints = {301, 302, 303, 307, 308}) + void shouldNotFollowARedirectOfTheTokenRequestWithALaxRedirectStrategy(final int redirectStatus) throws IOException { + final HttpServer target = tokenServer(); + try { + location = "http://127.0.0.1:" + target.getAddress().getPort() + "/elsewhere"; + respond(redirectStatus, "text/plain", ""); + final OAuthSdkCredentials credentials = new OAuthSdkCredentials( + HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy()), tokenUri(), + "client_id", CLIENT_SECRET, EnumSet.of(OAuthScope.GATEWAY)); + + final CheckoutException exception = assertThrows(CheckoutException.class, + () -> credentials.getAuthorization(SdkAuthorizationType.OAUTH)); + + assertEquals(TOKEN_REQUEST_FAILED + redirectStatus, exception.getMessage()); + assertEquals(0, targetRequests.get()); + } finally { + target.stop(0); + } + } + + @Test + void shouldKeepTheClientRequestConfigurationOfTheTokenRequest() throws IOException { + try (ServerSocket socket = new ServerSocket(0, 1, InetAddress.getByName("127.0.0.1"))) { + final URI uri = URI.create("http://127.0.0.1:" + socket.getLocalPort() + "/connect/token"); + final RequestConfig shortTimeout = RequestConfig.custom().setSocketTimeout(300).build(); + final OAuthSdkCredentials credentials = new OAuthSdkCredentials( + HttpClientBuilder.create().setDefaultRequestConfig(shortTimeout), uri, + "client_id", CLIENT_SECRET, EnumSet.of(OAuthScope.GATEWAY)); + + final CheckoutException exception = assertTimeoutPreemptively(Duration.ofSeconds(10), + () -> assertThrows(CheckoutException.class, + () -> credentials.getAuthorization(SdkAuthorizationType.OAUTH))); + + assertInstanceOf(CheckoutAuthorizationException.class, exception); + assertInstanceOf(SocketTimeoutException.class, exception.getCause()); + } + } + + @Test + void shouldNotRequestATokenWhenTheCredentialsAreCreated() { + respond(200, "application/json", "{\"access_token\":\"tok_1\",\"expires_in\":3600}"); + + final OAuthSdkCredentials credentials = credentials(tokenUri()); + + assertEquals(0, requests.get()); + assertNotNull(credentials.getAuthorization(SdkAuthorizationType.OAUTH)); + assertEquals(1, requests.get()); + } + + @ParameterizedTest + @ValueSource(strings = {"SECRET_KEY", "PUBLIC_KEY"}) + void shouldRejectAnOperationThatDoesNotAcceptOAuth(final String type) { + respond(200, "application/json", "{\"access_token\":\"tok_1\",\"expires_in\":3600}"); + final SdkAuthorizationType authorizationType = SdkAuthorizationType.valueOf(type); + + final CheckoutAuthorizationException exception = assertThrows(CheckoutAuthorizationException.class, + () -> credentials(tokenUri()).getAuthorization(authorizationType)); + + assertEquals("Operation requires " + type + " authorization type", exception.getMessage()); + assertEquals(0, requests.get()); + } + + private HttpServer tokenServer() throws IOException { + final HttpServer target = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); + target.createContext("/", exchange -> { + targetRequests.incrementAndGet(); + final byte[] response = "{\"access_token\":\"tok_from_redirect\",\"expires_in\":3600}" + .getBytes(StandardCharsets.UTF_8); + exchange.getResponseHeaders().add("Content-Type", "application/json"); + exchange.sendResponseHeaders(200, response.length); + try (OutputStream out = exchange.getResponseBody()) { + out.write(response); + } + }); + target.start(); + return target; + } + +} From 32b5ae90104c6c56444a4b7f28672fb222000a19 Mon Sep 17 00:00:00 2001 From: rodrigojara-cko Date: Fri, 20 Nov 2026 11:50:18 +0100 Subject: [PATCH 2/2] fix(client): generic authorization URI error message --- src/main/java/com/checkout/OAuthSdkCredentials.java | 2 +- .../java/com/checkout/OAuthSdkCredentialsTokenRequestTest.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/checkout/OAuthSdkCredentials.java b/src/main/java/com/checkout/OAuthSdkCredentials.java index 4760f60d6..c96ac89a7 100644 --- a/src/main/java/com/checkout/OAuthSdkCredentials.java +++ b/src/main/java/com/checkout/OAuthSdkCredentials.java @@ -44,7 +44,7 @@ @Slf4j final class OAuthSdkCredentials extends SdkCredentials { - private static final String INVALID_AUTHORIZATION_URI = "OAuth authorization URI must be an absolute https URI"; + private static final String INVALID_AUTHORIZATION_URI = "OAuth authorization URI is invalid"; private static final String TOKEN_REQUEST_FAILED = "OAuth token request failed with status "; private static final String INVALID_TOKEN_RESPONSE = "OAuth token response is invalid"; private static final String AUTHENTICATION_FAILED_WITH_ERROR = "OAuth client_credentials authentication failed with error: %s"; diff --git a/src/test/java/com/checkout/OAuthSdkCredentialsTokenRequestTest.java b/src/test/java/com/checkout/OAuthSdkCredentialsTokenRequestTest.java index feb7d9441..907bbc099 100644 --- a/src/test/java/com/checkout/OAuthSdkCredentialsTokenRequestTest.java +++ b/src/test/java/com/checkout/OAuthSdkCredentialsTokenRequestTest.java @@ -42,7 +42,7 @@ class OAuthSdkCredentialsTokenRequestTest { private static final String ECHO = "{{request}}"; private static final String TOKEN_REQUEST_FAILED = "OAuth token request failed with status "; private static final String INVALID_TOKEN_RESPONSE = "OAuth token response is invalid"; - private static final String INVALID_URI = "OAuth authorization URI must be an absolute https URI"; + private static final String INVALID_URI = "OAuth authorization URI is invalid"; private HttpServer server; private volatile int status;