diff --git a/README.md b/README.md index 2ce185db1..e57774c53 100644 --- a/README.md +++ b/README.md @@ -445,9 +445,11 @@ In case that you want to use an integrator or mock server, you can specify your final CustomEnvironment environment = CustomEnvironment.builder() .checkoutApi(create("https://the.base.uri/")) // the uri for all Checkout operations .oAuthAuthorizationApi(create("https://the.oauth.uri/connect/token")) // the uri used for OAUTH authorization, only required for OAuth operations - .filesApi(create("https://the.files.uri/")) // the uri used for Files operations, only required for Accounts module - .transfersApi(create("https://the.transfers.uri/")) // the uri used for Transfer operations, only required for Transfers module - .balancesApi(create("https://the.balances.uri/")) // the uri used for Balances operations, only required for Balances module + .filesApi(create("https://the.files.uri/")) // the uri used for Files operations (Accounts module) + .transfersApi(create("https://the.transfers.uri/")) // the uri used for Transfers operations + .balancesApi(create("https://the.balances.uri/")) // the uri used for Balances operations + .forwardApi(create("https://the.forward.uri/")) // the uri used for Forward operations + .identityApi(create("https://the.identity.uri/")) // the uri used for Identity operations .sandbox(false) // flag to determine if Sanbox or Production configured, default false .build(); @@ -459,7 +461,15 @@ final CheckoutApi checkoutApi = CheckoutSdk.builder() .build(); ``` -You don't need to specify all the previous URI's, only the ones for the modules that you're going to use. +The SDK creates a client for every module when it is built, so set `checkoutApi`, `filesApi`, `transfersApi`, +`balancesApi`, `forwardApi` and `identityApi`, also for the modules you do not call; `oAuthAuthorizationApi` is only +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 +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. ## Custom HttpClient diff --git a/src/main/java/com/checkout/AbstractCheckoutApmApi.java b/src/main/java/com/checkout/AbstractCheckoutApmApi.java index 9d634ccf4..abb01e2d6 100644 --- a/src/main/java/com/checkout/AbstractCheckoutApmApi.java +++ b/src/main/java/com/checkout/AbstractCheckoutApmApi.java @@ -46,7 +46,7 @@ public SepaClient sepaClient() { private ApiClient getBaseApiClient(final CheckoutConfiguration configuration) { - return new ApiClientImpl(configuration, new BaseUriStrategy(configuration)); + return new ApiClientImpl(configuration, new BaseUriStrategy(configuration), "checkoutApi"); } private static class BaseUriStrategy implements UriStrategy { diff --git a/src/main/java/com/checkout/AbstractClient.java b/src/main/java/com/checkout/AbstractClient.java index 774fcb10f..2e70cf55c 100644 --- a/src/main/java/com/checkout/AbstractClient.java +++ b/src/main/java/com/checkout/AbstractClient.java @@ -8,7 +8,8 @@ public abstract class AbstractClient { private static final char[] HEX = "0123456789ABCDEF".toCharArray(); private static final String INVALID_PATH_PARAMETER = - "Invalid path parameter: it must be valid text, not null, empty, '.' or '..'"; + "Invalid path parameter: it must be valid text, not null, empty, '.' or '..', " + + "and must not contain '/', '\\' or ASCII control characters"; protected final ApiClient apiClient; protected final CheckoutConfiguration configuration; @@ -37,8 +38,9 @@ protected SdkAuthorization sdkAuthorization() { * * @param pathParams the path segments, in order * @return the request path, relative to the base URI - * @throws CheckoutArgumentException if a parameter is null, empty, "." or "..", or is not valid - * UTF-16 text (an unpaired surrogate) + * @throws CheckoutArgumentException if a parameter is null, empty, "." or "..", contains "/", {@code \} + * or an ASCII control character (U+0000 to U+001F, U+007F), or is not + * valid UTF-16 text (an unpaired surrogate) */ protected static String buildPath(final String... pathParams) { final StringBuilder path = new StringBuilder(); @@ -53,17 +55,18 @@ protected static String buildPath(final String... pathParams) { /** * Percent-encodes a path parameter as UTF-8, keeping only the RFC 3986 unreserved characters - * (letters, digits, "-", ".", "_" and "~"), so the result is exactly one path segment. + * (letters, digits, "-", ".", "_" and "~"), so the result is exactly one path segment. "/", + * {@code \} and ASCII control characters are refused rather than encoded. */ private static String encodePathSegment(final String pathParam) { if (pathParam == null || pathParam.isEmpty() || ".".equals(pathParam) || "..".equals(pathParam) - || hasUnpairedSurrogate(pathParam)) { + || hasForbiddenCharacter(pathParam) || hasUnpairedSurrogate(pathParam)) { throw new CheckoutArgumentException(INVALID_PATH_PARAMETER); } final StringBuilder encoded = new StringBuilder(pathParam.length()); for (final byte b : pathParam.getBytes(StandardCharsets.UTF_8)) { final int c = b & 0xFF; - if (isUnreserved(c)) { + if (UriCharacters.isUnreserved(c)) { encoded.append((char) c); } else { encoded.append('%').append(HEX[c >> 4]).append(HEX[c & 0x0F]); @@ -72,9 +75,14 @@ private static String encodePathSegment(final String pathParam) { return encoded.toString(); } - private static boolean isUnreserved(final int c) { - return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') - || c == '-' || c == '.' || c == '_' || c == '~'; + private static boolean hasForbiddenCharacter(final String value) { + for (int i = 0; i < value.length(); i++) { + final char c = value.charAt(i); + if (c == '/' || c == '\\' || c <= 0x1F || c == 0x7F) { + return true; + } + } + return false; } private static boolean hasUnpairedSurrogate(final String value) { diff --git a/src/main/java/com/checkout/ApacheHttpClientTransport.java b/src/main/java/com/checkout/ApacheHttpClientTransport.java index 774cf9b10..58ce97f0f 100644 --- a/src/main/java/com/checkout/ApacheHttpClientTransport.java +++ b/src/main/java/com/checkout/ApacheHttpClientTransport.java @@ -41,7 +41,6 @@ import java.util.concurrent.Executor; import java.util.stream.Collectors; import java.util.function.Supplier; -import java.util.regex.Pattern; import io.github.resilience4j.circuitbreaker.CircuitBreaker; import io.github.resilience4j.ratelimiter.RateLimiter; import io.github.resilience4j.retry.Retry; @@ -64,9 +63,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 Pattern ENCODED_QUERY = Pattern.compile("[A-Za-z0-9._~*+%=&-]+"); private final URI baseUri; + private final String baseDirectory; private final CloseableHttpClient httpClient; private final Executor executor; private final TransportConfiguration transportConfiguration; @@ -75,15 +74,27 @@ class ApacheHttpClientTransport implements Transport { private static final ThreadLocal telemetryData = ThreadLocal.withInitial(RequestMetrics::new); + /** + * @param baseUri the base URI every request path is resolved against + * @param baseUriSetting the name of the setting the base URI comes from ("filesApi"), used in + * errors instead of the value + * @param httpClientBuilder the HTTP client builder + * @param executor the executor for asynchronous calls + * @param transportConfiguration the transport configuration + * @param configuration the SDK configuration + * @throws CheckoutArgumentException if the base URI is missing or invalid (see {@link BaseUri#normalise}) + */ ApacheHttpClientTransport( final URI baseUri, + final String baseUriSetting, final HttpClientBuilder httpClientBuilder, final Executor executor, final TransportConfiguration transportConfiguration, final CheckoutConfiguration configuration ) { - CheckoutUtils.validateParams("baseUri", baseUri, "httpClientBuilder", httpClientBuilder, "executor", executor); - this.baseUri = withRootPath(baseUri); + CheckoutUtils.validateParams(baseUriSetting, baseUri, "httpClientBuilder", httpClientBuilder, "executor", executor); + this.baseUri = BaseUri.normalise(baseUri, baseUriSetting); + this.baseDirectory = directoryOf(this.baseUri); this.httpClient = httpClientBuilder .setRedirectStrategy(new CustomAwsRedirectStrategy()) .build(); @@ -386,16 +397,19 @@ private HttpUriRequest buildRequest(final ClientOperation clientOperation, final /** * Resolves a request path against the base URI. The path must be relative and made of non-empty - * segments, none of them "." or ".." (also when percent-encoded or followed by ";"). It may end with - * an already encoded query ("?name=value&..." made only of unreserved characters, "%", "+", "=" - * and "&"), and never with a "#". The resolved URL must keep the scheme, host, port and base path - * of the base URI. + * segments of unreserved characters and "%XX" escapes, none of them "." or ".." (also when + * percent-encoded) and none containing an encoded "/", {@code \} or ASCII control character. It may + * end with an already encoded query ("?name=value&..." made only of unreserved characters, "*", + * "+", "=", "&" and "%" followed by two hex digits), and never with a "#". The resolved URL keeps + * the scheme and authority of the base URI, and its base directory (the path up to the last "/") is + * kept: a base URI without a trailing slash has its last path segment replaced, as + * {@link URI#resolve(String)} (RFC 3986) defines. * * @param path the request path, as built by {@code AbstractClient.buildPath} * @return the absolute request URL * @throws CheckoutArgumentException if the path is invalid or resolves outside the base URI */ - String getRequestUrl(final String path) { + private String getRequestUrl(final String path) { validateRequestPath(path); final URI resolved = baseUri.resolve(path); if (!isUnderBaseUri(resolved)) { @@ -409,12 +423,13 @@ String getRequestUrl(final String path) { } /** - * A base URI with no path ("https://api.example.com") resolves "payments" to the host - * "api.example.compayments"; the root path "/" keeps the request on the configured host. + * The base directory (the path up to the last "/") that {@link URI#resolve(String)} keeps, read from a resolved probe so it + * matches resolve exactly (it drops the last segment and collapses empty ones). Used only by the + * defence-in-depth check in {@link #isUnderBaseUri(URI)}. */ - private static URI withRootPath(final URI baseUri) { - final String path = baseUri.getRawPath(); - return baseUri.isAbsolute() && !baseUri.isOpaque() && (path == null || path.isEmpty()) ? baseUri.resolve("/") : baseUri; + private static String directoryOf(final URI baseUri) { + final String probe = baseUri.resolve("probe").getRawPath(); + return probe.substring(0, probe.length() - "probe".length()); } private static void validateRequestPath(final String path) { @@ -422,34 +437,28 @@ private static void validateRequestPath(final String path) { throw new CheckoutArgumentException(INVALID_REQUEST_PATH); } final int queryStart = path.indexOf('?'); - if (queryStart >= 0 && !ENCODED_QUERY.matcher(path.substring(queryStart + 1)).matches()) { + if (queryStart >= 0 && !UriCharacters.isPercentEncoded(path.substring(queryStart + 1), UriCharacters.QUERY_EXTRA)) { throw new CheckoutArgumentException(INVALID_REQUEST_PATH); } final String pathOnly = queryStart >= 0 ? path.substring(0, queryStart) : path; for (final String segment : pathOnly.split("/", -1)) { - if (isEmptyOrDotSegment(segment)) { + if (segment.isEmpty() || UriCharacters.isDotSegment(segment) || !UriCharacters.isPercentEncoded(segment, "") + || UriCharacters.hasEncodedSeparatorOrControl(segment)) { throw new CheckoutArgumentException(INVALID_REQUEST_PATH); } } } - private static boolean isEmptyOrDotSegment(final String segment) { - final int parameters = segment.indexOf(';'); - final String name = (parameters >= 0 ? segment.substring(0, parameters) : segment).replaceAll("(?i)%2e", "."); - return name.isEmpty() || ".".equals(name) || "..".equals(name); - } - /** - * True when the URL has the scheme, host and port of the base URI and a path under the base URI's - * directory, the part of its path that {@link URI#resolve(String)} keeps. + * True when the URL has the scheme and authority of the base URI and a path under the base URI's + * directory. The raw authority is compared because {@link URI#getHost()} is null for host names + * that are not valid DNS names, such as those with "_". Defence in depth: a path that passed + * {@link #validateRequestPath(String)} always resolves under the base URI, so this check is not + * expected to fail; it guards against a change to either rule. */ private boolean isUnderBaseUri(final URI resolved) { - final String basePath = baseUri.getRawPath() == null ? "" : baseUri.getRawPath(); - final String baseDirectory = basePath.substring(0, basePath.lastIndexOf('/') + 1); return baseUri.getScheme().equalsIgnoreCase(resolved.getScheme()) - && baseUri.getHost() != null - && baseUri.getHost().equalsIgnoreCase(resolved.getHost()) - && baseUri.getPort() == resolved.getPort() + && baseUri.getRawAuthority().equalsIgnoreCase(resolved.getRawAuthority()) && resolved.getRawPath() != null && resolved.getRawPath().startsWith(baseDirectory) && resolved.getRawFragment() == null; diff --git a/src/main/java/com/checkout/ApiClientImpl.java b/src/main/java/com/checkout/ApiClientImpl.java index 0478c1952..ac654ef8a 100644 --- a/src/main/java/com/checkout/ApiClientImpl.java +++ b/src/main/java/com/checkout/ApiClientImpl.java @@ -34,11 +34,27 @@ public class ApiClientImpl implements ApiClient { private final CheckoutConfiguration configuration; private final java.util.concurrent.Executor executor; + /** + * Creates an API client for the base URI the strategy returns. + * + * @param configuration the SDK configuration + * @param uriStrategy the strategy returning the base URI + * @throws CheckoutArgumentException if the base URI is missing or invalid; the error names + * "uriStrategy", never the URI + */ public ApiClientImpl(final CheckoutConfiguration configuration, final UriStrategy uriStrategy) { + this(configuration, uriStrategy, "uriStrategy"); + } + + /** + * Creates an API client for the base URI the strategy returns, naming the setting it comes from in + * errors ("filesApi") instead of the URI. + */ + ApiClientImpl(final CheckoutConfiguration configuration, final UriStrategy uriStrategy, final String baseUriSetting) { this.serializer = new GsonSerializer(); this.configuration = configuration; this.executor = configuration.getExecutor(); - this.transport = new ApacheHttpClientTransport(uriStrategy.getUri(), configuration.getHttpClientBuilder(), configuration.getExecutor(), configuration.getTransportConfiguration(), configuration); + this.transport = new ApacheHttpClientTransport(uriStrategy.getUri(), baseUriSetting, configuration.getHttpClientBuilder(), configuration.getExecutor(), configuration.getTransportConfiguration(), configuration); } @Override diff --git a/src/main/java/com/checkout/BaseUri.java b/src/main/java/com/checkout/BaseUri.java new file mode 100644 index 000000000..9149a56e7 --- /dev/null +++ b/src/main/java/com/checkout/BaseUri.java @@ -0,0 +1,175 @@ +package com.checkout; + +import java.net.URI; +import java.net.URISyntaxException; + +/** + * Validation of configured base URIs and the environment subdomain rebuild, shared by the transport + * and {@link EnvironmentSubdomain}. Errors name the setting ("filesApi"), never the value. + */ +final class BaseUri { + + private static final String INVALID_BASE_URI = "Invalid base URI for %s: it must be an absolute http or https URI " + + "with an ASCII host written without percent-encoding, an optional port from 1 to 65535, no user information, " + + "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"; + private static final int MAX_PORT = 65535; + + private BaseUri() { + } + + /** + * Checks a base URI and returns it with a normalised path. It must be absolute http or https with a + * non-empty host, an optional port from 1 to 65535 and no user information, and its authority must + * be visible ASCII and hold no "%" (an escape there reads differently once decoded). After normalising, no path + * segment may be "." or ".." (also when percent-encoded, and also before a ";" parameter) or hold an + * encoded "/", {@code \} or ASCII control character. A base URI with no path gets the root path "/". + * Request paths are resolved against the base directory, the path up to its last "/". + * + * @param baseUri the configured base URI + * @param setting the name of the setting it comes from, used in errors instead of the value + * @return the normalised base URI + * @throws CheckoutArgumentException if the base URI is missing or invalid + */ + static URI normalise(final URI baseUri, final String setting) { + if (baseUri == null) { + throw new CheckoutArgumentException(setting + " cannot be null"); + } + final String scheme = baseUri.getScheme(); + final String authority = baseUri.getRawAuthority(); + if (scheme == null || baseUri.isOpaque() || authority == null || authority.indexOf('@') >= 0 + || authority.indexOf('%') >= 0 || !isVisibleAscii(authority) || hostOf(authority) == null + || !("http".equalsIgnoreCase(scheme) || "https".equalsIgnoreCase(scheme))) { + throw invalid(INVALID_BASE_URI, setting); + } + final String path = baseUri.getRawPath(); + final URI normalised = path == null || path.isEmpty() ? baseUri.resolve("/") : baseUri.normalize(); + for (final String segment : normalised.getRawPath().split("/", -1)) { + final int parameters = segment.indexOf(';'); + if (UriCharacters.isDotSegment(parameters >= 0 ? segment.substring(0, parameters) : segment) + || UriCharacters.hasEncodedSeparatorOrControl(segment)) { + throw invalid(INVALID_BASE_URI, setting); + } + } + return normalised; + } + + /** + * 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). + * + * @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 + */ + 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) { + throw invalid(INVALID_SUBDOMAIN_URI, setting); + } + final int hostStart = authority.lastIndexOf('@') + 1; + final String host = hostOf(authority.substring(hostStart)); + 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)); + if (uri.getRawPath() != null) { + rebuilt.append(uri.getRawPath()); + } + if (uri.getRawQuery() != null) { + rebuilt.append('?').append(uri.getRawQuery()); + } + if (uri.getRawFragment() != null) { + rebuilt.append('#').append(uri.getRawFragment()); + } + try { + return new URI(rebuilt.toString()); + } catch (final URISyntaxException e) { + throw invalid(INVALID_SUBDOMAIN_URI, setting); + } + } + + /** + * Reads the host from a raw authority without user information, because {@link URI#getHost()} is + * null for host names that are not valid DNS names, such as those with "_". + * + * @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) { + 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); + if (host.isEmpty() || (!port.isEmpty() && port.charAt(0) != ':')) { + return null; + } + int value = 0; + for (int i = 1; i < port.length(); i++) { + final char c = port.charAt(i); + if (c < '0' || c > '9') { + return null; + } + value = value * 10 + (c - '0'); + if (value > MAX_PORT) { + return null; + } + } + return port.length() > 1 && value == 0 ? null : host; + } + + /** + * True when the host can take a subdomain: not an IPv6 literal, every label (ignoring one trailing + * ".") non-empty, made of ASCII letters, digits, "-" and "_", and neither starting nor ending with + * "-", and the last label starting with an ASCII letter, which leaves out IPv4 addresses in every + * notation ("127.0.0.1", "127.1", "2130706433", "0x7f000001", "017700000001"). + */ + private static boolean isDomainName(final String host) { + final String name = host.endsWith(".") ? host.substring(0, host.length() - 1) : host; + final String[] labels = name.split("\\.", -1); + for (final String label : labels) { + if (label.isEmpty() || label.charAt(0) == '-' || label.charAt(label.length() - 1) == '-') { + return false; + } + for (int i = 0; i < label.length(); i++) { + final char c = label.charAt(i); + if (!isAsciiLetter(c) && !(c >= '0' && c <= '9') && c != '-' && c != '_') { + return false; + } + } + } + return isAsciiLetter(labels[labels.length - 1].charAt(0)); + } + + private static boolean isAsciiLetter(final char c) { + return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z'); + } + + private static boolean isVisibleAscii(final String value) { + for (int i = 0; i < value.length(); i++) { + final char c = value.charAt(i); + if (c <= ' ' || c > '~') { + return false; + } + } + return true; + } + + private static CheckoutArgumentException invalid(final String message, final String setting) { + return new CheckoutArgumentException(String.format(message, setting)); + } +} diff --git a/src/main/java/com/checkout/CheckoutApiImpl.java b/src/main/java/com/checkout/CheckoutApiImpl.java index 8865cfe2c..ad519ec44 100644 --- a/src/main/java/com/checkout/CheckoutApiImpl.java +++ b/src/main/java/com/checkout/CheckoutApiImpl.java @@ -309,23 +309,23 @@ public MetadataClient metadataClient() { public OnboardingSimulatorClient onboardingSimulatorClient() { return onboardingSimulatorClient; } private ApiClient getFilesClient(final CheckoutConfiguration configuration) { - return new ApiClientImpl(configuration, new FilesApiUriStrategy(configuration)); + return new ApiClientImpl(configuration, new FilesApiUriStrategy(configuration), "filesApi"); } private ApiClient getTransfersClient(final CheckoutConfiguration configuration) { - return new ApiClientImpl(configuration, new TransfersApiUriStrategy(configuration)); + return new ApiClientImpl(configuration, new TransfersApiUriStrategy(configuration), "transfersApi"); } private ApiClient getBalancesClient(final CheckoutConfiguration configuration) { - return new ApiClientImpl(configuration, new BalancesApiUriStrategy(configuration)); + return new ApiClientImpl(configuration, new BalancesApiUriStrategy(configuration), "balancesApi"); } private ApiClient getForwardClient(final CheckoutConfiguration configuration) { - return new ApiClientImpl(configuration, new ForwardApiUriStrategy(configuration)); + return new ApiClientImpl(configuration, new ForwardApiUriStrategy(configuration), "forwardApi"); } private ApiClient getIdentityClient(final CheckoutConfiguration configuration) { - return new ApiClientImpl(configuration, new IdentityApiUriStrategy(configuration)); + return new ApiClientImpl(configuration, new IdentityApiUriStrategy(configuration), "identityApi"); } private static class FilesApiUriStrategy implements UriStrategy { diff --git a/src/main/java/com/checkout/EnvironmentSubdomain.java b/src/main/java/com/checkout/EnvironmentSubdomain.java index 40aed4b51..84545c4a1 100644 --- a/src/main/java/com/checkout/EnvironmentSubdomain.java +++ b/src/main/java/com/checkout/EnvironmentSubdomain.java @@ -1,10 +1,13 @@ package com.checkout; import java.net.URI; -import java.net.URISyntaxException; import java.util.regex.Pattern; import java.util.regex.Matcher; +/** + * The base URIs of an environment moved to the merchant-specific subdomain: the subdomain is + * prepended to the host of {@code checkoutApi} and {@code oAuthAuthorizationApi}. + */ public final class EnvironmentSubdomain { private static final Pattern SUBDOMAIN_PATTERN = Pattern.compile("^(?:pl-)?[a-z0-9]+$"); @@ -12,42 +15,43 @@ public final class EnvironmentSubdomain { private URI checkoutApi; private URI oAuthAuthorizationApi; + /** + * 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. + * + * @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 + * cannot take a subdomain (empty, an IPv6 literal or an IPv4 address); + * the error names the setting, never the value + */ public EnvironmentSubdomain(IEnvironment environment, String subdomain) { - checkoutApi = createUrlWithSubdomain(environment.getCheckoutApi(), subdomain); - oAuthAuthorizationApi = createUrlWithSubdomain(environment.getOAuthAuthorizationApi(), subdomain); + validateSubdomain(subdomain); + checkoutApi = BaseUri.withSubdomain(BaseUri.normalise(environment.getCheckoutApi(), "checkoutApi"), subdomain, "checkoutApi"); + oAuthAuthorizationApi = BaseUri.withSubdomain(environment.getOAuthAuthorizationApi(), subdomain, "oAuthAuthorizationApi"); } + /** + * @return the {@code checkoutApi} base URI on the subdomain host + */ public URI getCheckoutApi() { return checkoutApi; } + /** + * @return the {@code oAuthAuthorizationApi} URI on the subdomain host + */ public URI getOAuthAuthorizationApi() { return oAuthAuthorizationApi; } - /** - * Applies subdomain transformation to any given URI, prepending the subdomain to the host. - * - * @param originalUrl the original URI to transform - * @param subdomain the subdomain to prepend - * @return the transformed URI with subdomain - * @throws CheckoutArgumentException if the subdomain is not a valid merchant-specific subdomain - */ - private static URI createUrlWithSubdomain(URI originalUrl, String subdomain) { - Matcher matcher = subdomain == null ? null : SUBDOMAIN_PATTERN.matcher(subdomain); + private static void validateSubdomain(final String subdomain) { + final Matcher matcher = subdomain == null ? null : SUBDOMAIN_PATTERN.matcher(subdomain); if (matcher == null || !matcher.matches()) { throw new CheckoutArgumentException("invalid environment subdomain - provide your merchant-specific subdomain, typically your client ID excluding the cli_ prefix (see https://api-reference.checkout.com/#section/Base-URLs)"); } - - String host = originalUrl.getHost(); - String scheme = originalUrl.getScheme(); - int port = originalUrl.getPort(); - String newHost = subdomain + "." + host; - try { - return new URI(scheme, null, newHost, port, originalUrl.getPath(), originalUrl.getQuery(), originalUrl.getFragment()); - } catch (final URISyntaxException e) { - throw new CheckoutException(e); - } } } diff --git a/src/main/java/com/checkout/UriCharacters.java b/src/main/java/com/checkout/UriCharacters.java new file mode 100644 index 000000000..5cc2ef942 --- /dev/null +++ b/src/main/java/com/checkout/UriCharacters.java @@ -0,0 +1,85 @@ +package com.checkout; + +import java.util.regex.Pattern; + +/** + * Character rules shared by the path builder and the transport, so both read the same grammar. + */ +final class UriCharacters { + + /** Characters a query string may hold unencoded besides the unreserved ones. */ + static final String QUERY_EXTRA = "*+=&"; + + private static final Pattern ENCODED_SEPARATOR_OR_CONTROL = + Pattern.compile("%(?:2F|5C|[01][0-9A-F]|7F)", Pattern.CASE_INSENSITIVE); + + private UriCharacters() { + } + + /** + * True for the RFC 3986 unreserved characters: ASCII letters and digits, "-", ".", "_" and "~". + * + * @param c a character or a byte value from 0 to 255 + * @return whether it may appear unencoded in a path segment + */ + static boolean isUnreserved(final int c) { + return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') + || c == '-' || c == '.' || c == '_' || c == '~'; + } + + /** + * True when the value is not empty and every character is unreserved, one of {@code extra}, or a + * "%" followed by two hex digits. One pass, no backtracking. + * + * @param value the text to check + * @param extra characters allowed besides the unreserved ones ("" for a path segment, + * {@link #QUERY_EXTRA} for a query string) + * @return whether the value is already percent-encoded under that grammar + */ + static boolean isPercentEncoded(final String value, final String extra) { + if (value.isEmpty()) { + return false; + } + int i = 0; + while (i < value.length()) { + final char c = value.charAt(i); + if (c == '%') { + if (i + 2 >= value.length() || !isHexDigit(value.charAt(i + 1)) || !isHexDigit(value.charAt(i + 2))) { + return false; + } + i += 3; + } else if (isUnreserved(c) || extra.indexOf(c) >= 0) { + i++; + } else { + return false; + } + } + return true; + } + + /** + * True for "." and "..", also when one or both dots are percent-encoded ("%2e" or "%2E"). + * + * @param segment one path segment, without its ";" parameters + * @return whether it is a dot segment + */ + static boolean isDotSegment(final String segment) { + final String name = segment.replace("%2e", ".").replace("%2E", "."); + return ".".equals(name) || "..".equals(name); + } + + /** + * True when the value holds an encoded "/", {@code \} or ASCII control character ("%2F", "%5C", + * "%00" to "%1F", "%7F", in any case). + * + * @param value the raw text to check + * @return whether it holds one of those escapes + */ + static boolean hasEncodedSeparatorOrControl(final String value) { + return ENCODED_SEPARATOR_OR_CONTROL.matcher(value).find(); + } + + private static boolean isHexDigit(final char c) { + return (c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') || (c >= 'a' && c <= 'f'); + } +} diff --git a/src/main/java/com/checkout/customers/CustomersClient.java b/src/main/java/com/checkout/customers/CustomersClient.java index 06c053d9d..5d8625234 100644 --- a/src/main/java/com/checkout/customers/CustomersClient.java +++ b/src/main/java/com/checkout/customers/CustomersClient.java @@ -5,23 +5,83 @@ import java.util.concurrent.CompletableFuture; +/** + * Client for the customers API: create, retrieve, update and delete customers. + */ public interface CustomersClient { + /** + * Gets the details of a customer and their payment instruments ({@code GET /customers/{identifier}}). + * + * @param customerId the customer's ID, or their email. An identifier is sent as exactly one path + * segment, so an email containing "/", {@code \} or an ASCII control character is + * refused with a {@link com.checkout.CheckoutArgumentException}: use the customer's + * ID instead + * @return the customer details + */ CompletableFuture get(String customerId); + /** + * Creates a customer ({@code POST /customers}). + * + * @param customerRequest the customer details + * @return the ID of the new customer + */ CompletableFuture create(CustomerRequest customerRequest); + /** + * Updates the details of a customer ({@code PATCH /customers/{identifier}}). + * + * @param customerId the customer's ID + * @param customerRequest the details to update + * @return an empty response + */ CompletableFuture update(String customerId, CustomerRequest customerRequest); + /** + * Deletes a customer and their linked payment instruments ({@code DELETE /customers/{identifier}}). + * + * @param customerId the customer's ID + * @return an empty response + */ CompletableFuture delete(String customerId); // Synchronous methods + + /** + * Gets the details of a customer and their payment instruments ({@code GET /customers/{identifier}}). + * + * @param customerId the customer's ID, or their email. An identifier is sent as exactly one path + * segment, so an email containing "/", {@code \} or an ASCII control character is + * refused with a {@link com.checkout.CheckoutArgumentException}: use the customer's + * ID instead + * @return the customer details + */ CustomerResponse getSync(String customerId); + /** + * Creates a customer ({@code POST /customers}). + * + * @param customerRequest the customer details + * @return the ID of the new customer + */ IdResponse createSync(CustomerRequest customerRequest); + /** + * Updates the details of a customer ({@code PATCH /customers/{identifier}}). + * + * @param customerId the customer's ID + * @param customerRequest the details to update + * @return an empty response + */ EmptyResponse updateSync(String customerId, CustomerRequest customerRequest); + /** + * Deletes a customer and their linked payment instruments ({@code DELETE /customers/{identifier}}). + * + * @param customerId the customer's ID + * @return an empty response + */ EmptyResponse deleteSync(String customerId); } diff --git a/src/test/java/com/checkout/AbstractClientBuildPathTest.java b/src/test/java/com/checkout/AbstractClientBuildPathTest.java index 02a85f768..225d08e17 100644 --- a/src/test/java/com/checkout/AbstractClientBuildPathTest.java +++ b/src/test/java/com/checkout/AbstractClientBuildPathTest.java @@ -17,15 +17,10 @@ class AbstractClientBuildPathTest { private static Stream encodedValues() { return Stream.of( Arguments.of("pay_123", "payments/pay_123"), - Arguments.of("pay_1/refunds", "payments/pay_1%2Frefunds"), - Arguments.of("../payments/pay_1", "payments/..%2Fpayments%2Fpay_1"), Arguments.of("pay_1?x=1", "payments/pay_1%3Fx%3D1"), Arguments.of("pay_1#x", "payments/pay_1%23x"), Arguments.of("pay_1%2Frefunds", "payments/pay_1%252Frefunds"), - Arguments.of("pay_1\\refunds", "payments/pay_1%5Crefunds"), Arguments.of("my secret", "payments/my%20secret"), - Arguments.of("pay_1\r\nX: y", "payments/pay_1%0D%0AX%3A%20y"), - Arguments.of("pay_1\u0000", "payments/pay_1%00"), Arguments.of("clé", "payments/cl%C3%A9"), Arguments.of("a.b-c_d~e", "payments/a.b-c_d~e"), Arguments.of("...", "payments/..."), @@ -46,9 +41,19 @@ void shouldKeepPlainPathsUnchanged() { @ParameterizedTest @NullSource - @ValueSource(strings = {"", ".", "..", "\ud800", "a\udc00b", "\ud83d"}) + @ValueSource(strings = {"", ".", "..", "\ud800", "a\udc00b", "\ud83d", + "pay_1/refunds", "../payments/pay_1", "pay_1\\refunds", "pay_1\r\nX: y", "pay_1\u0000", + "pay_1\t", "pay_1\u001f", "pay_1\u007f"}) void shouldRefuseInvalidPathParameters(final String value) { - assertThrows(CheckoutArgumentException.class, () -> AbstractClient.buildPath("payments", value, "refunds")); + final CheckoutArgumentException exception = assertThrows(CheckoutArgumentException.class, + () -> AbstractClient.buildPath("payments", value, "refunds")); + assertEquals("Invalid path parameter: it must be valid text, not null, empty, '.' or '..', " + + "and must not contain '/', '\\' or ASCII control characters", exception.getMessage()); + } + + @Test + void shouldKeepCharactersOutsideTheForbiddenSetEncoded() { + assertEquals("payments/pay_1%C2%80%20%25", AbstractClient.buildPath("payments", "pay_1\u0080 %")); } } diff --git a/src/test/java/com/checkout/ApacheHttpClientTransportRequestUrlTest.java b/src/test/java/com/checkout/ApacheHttpClientTransportRequestUrlTest.java index 6d4ffcf5b..c7ac01430 100644 --- a/src/test/java/com/checkout/ApacheHttpClientTransportRequestUrlTest.java +++ b/src/test/java/com/checkout/ApacheHttpClientTransportRequestUrlTest.java @@ -1,8 +1,10 @@ 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.assertInstanceOf; import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; @@ -13,6 +15,7 @@ import java.net.URI; import java.nio.charset.StandardCharsets; import java.nio.file.Files; +import java.time.Duration; import java.util.ArrayList; import java.util.Collections; import java.util.List; @@ -44,6 +47,7 @@ class ApacheHttpClientTransportRequestUrlTest { private final SdkAuthorization authorization = new SdkAuthorization(PlatformType.DEFAULT, "sk_test"); private final List receivedPaths = Collections.synchronizedList(new ArrayList<>()); private final List receivedQueries = Collections.synchronizedList(new ArrayList<>()); + private final List receivedHosts = Collections.synchronizedList(new ArrayList<>()); private final List executors = new ArrayList<>(); private HttpServer server; @@ -57,6 +61,7 @@ void startServer() throws IOException { server.createContext("/", exchange -> { receivedPaths.add(exchange.getRequestURI().getRawPath()); receivedQueries.add(String.valueOf(exchange.getRequestURI().getRawQuery())); + receivedHosts.add(exchange.getRequestHeaders().getFirst("Host")); final byte[] body = "{}".getBytes(StandardCharsets.UTF_8); exchange.getResponseHeaders().add("Content-Type", "application/json"); exchange.sendResponseHeaders(200, body.length); @@ -73,40 +78,134 @@ void stopServerAndExecutors() { executors.forEach(ExecutorService::shutdownNow); } - private ApacheHttpClientTransport transport(final URI baseUri) { + private ApacheHttpClientTransport transport(final URI baseUri, final HttpClientBuilder httpClientBuilder) { final ExecutorService executor = Executors.newSingleThreadExecutor(); executors.add(executor); - return new ApacheHttpClientTransport(baseUri, HttpClientBuilder.create(), executor, + return new ApacheHttpClientTransport(baseUri, "checkoutApi", httpClientBuilder, executor, new DefaultTransportConfiguration(), mock(CheckoutConfiguration.class)); } + private ApacheHttpClientTransport transport(final URI baseUri) { + return transport(baseUri, HttpClientBuilder.create()); + } + + /** Sends a GET through the public transport method and returns the URL the HTTP client received. */ + private String requestUrl(final URI baseUri, final String path) { + final RecordingHttpClientBuilder recorder = new RecordingHttpClientBuilder(); + transport(baseUri, recorder).invokeSync(ClientOperation.GET, path, authorization, null, null, Collections.emptyMap()); + assertEquals(1, recorder.requests.size()); + return recorder.requests.get(0); + } + + /** Asserts the public transport method refuses the path before anything is sent. */ + private void assertRefused(final URI baseUri, final String path) { + final RecordingHttpClientBuilder recorder = new RecordingHttpClientBuilder(); + final ApacheHttpClientTransport transport = transport(baseUri, recorder); + assertThrows(CheckoutArgumentException.class, + () -> transport.invokeSync(ClientOperation.GET, path, authorization, null, null, Collections.emptyMap())); + assertTrue(recorder.requests.isEmpty(), "nothing is sent"); + } + private ApacheHttpClientTransport localTransport() { return transport(URI.create("http://127.0.0.1:" + server.getAddress().getPort() + "/")); } @Test void shouldResolveValidRequestPaths() { - final ApacheHttpClientTransport transport = transport(SANDBOX); - - assertEquals("https://api.sandbox.checkout.com/payments/pay_123", transport.getRequestUrl(VALID_PATH)); - assertEquals("https://api.sandbox.checkout.com/payments/pay_1%2Frefunds", transport.getRequestUrl("payments/pay_1%2Frefunds")); - assertEquals("https://api.sandbox.checkout.com/payments/...", transport.getRequestUrl("payments/...")); - assertEquals("https://api.sandbox.checkout.com/ideal-external/issuers", transport.getRequestUrl("ideal-external/issuers")); + assertEquals("https://api.sandbox.checkout.com/payments/pay_123", requestUrl(SANDBOX, VALID_PATH)); + assertEquals("https://api.sandbox.checkout.com/payments/pay_1%252Frefunds", requestUrl(SANDBOX, "payments/pay_1%252Frefunds")); + assertEquals("https://api.sandbox.checkout.com/payments/...", requestUrl(SANDBOX, "payments/...")); + assertEquals("https://api.sandbox.checkout.com/ideal-external/issuers", requestUrl(SANDBOX, "ideal-external/issuers")); assertEquals("https://api.sandbox.checkout.com/event-types?version=v2%26x%3D1%23y", - transport.getRequestUrl("event-types?version=v2%26x%3D1%23y")); + requestUrl(SANDBOX, "event-types?version=v2%26x%3D1%23y")); } @Test void shouldResolveUnderCustomBaseUris() { assertEquals("https://proxy.example/checkout/payments/pay_123", - transport(URI.create("https://proxy.example/checkout/")).getRequestUrl(VALID_PATH)); + requestUrl(URI.create("https://proxy.example/checkout/"), VALID_PATH)); assertEquals("https://proxy.example/payments/pay_123", - transport(URI.create("https://proxy.example")).getRequestUrl(VALID_PATH)); + requestUrl(URI.create("https://proxy.example"), VALID_PATH)); assertEquals("https://proxy.example:8443/payments/pay_123", - transport(URI.create("https://proxy.example:8443")).getRequestUrl(VALID_PATH)); - // Without a trailing slash, URI.resolve replaces the last base segment, as it always has. + requestUrl(URI.create("https://proxy.example:8443"), VALID_PATH)); + // The base directory (the path up to the last "/") is kept, so without a trailing slash the last segment is replaced. + assertEquals("https://proxy.example/payments/pay_123", + requestUrl(URI.create("https://proxy.example/checkout"), VALID_PATH)); + } + + @Test + void shouldResolveUnderBaseUrisWithUnderscoreHostsOrUnnormalisedPaths() { + assertEquals("https://proxy_host.example/payments/pay_123", + requestUrl(URI.create("https://proxy_host.example/"), VALID_PATH)); + assertEquals("http://checkout_proxy:8080/api/payments/pay_123", + requestUrl(URI.create("http://checkout_proxy:8080/api/"), VALID_PATH)); + assertEquals("https://proxy.example/b/payments/pay_123", + requestUrl(URI.create("https://proxy.example/a/../b/"), VALID_PATH)); assertEquals("https://proxy.example/payments/pay_123", - transport(URI.create("https://proxy.example/checkout")).getRequestUrl(VALID_PATH)); + requestUrl(URI.create("https://proxy.example//"), VALID_PATH)); + } + + @ParameterizedTest + @ValueSource(strings = {"api.example.com/", "/checkout/", "mailto:x@example.com", "https:///payments/", "http://:80/", + "https://user@/", "https://@/", "https://user:pass@proxy.example/", "https://proxy.example/../x/", + "https://proxy.example/%2e%2e/x/", "https://proxy.example:x/"}) + void shouldRefuseBaseUrisThatAreNotAbsoluteWithAHostOrHoldUserInfoOrDotSegments(final String baseUri) { + final CheckoutArgumentException exception = assertThrows(CheckoutArgumentException.class, () -> transport(URI.create(baseUri))); + assertTrue(exception.getMessage().startsWith("Invalid base URI for checkoutApi:"), exception::getMessage); + assertFalse(exception.getMessage().contains(baseUri), exception::getMessage); + } + + @Test + void shouldSendRequestsToTheConfiguredHostAndPort() { + final int port = server.getAddress().getPort(); + transport(URI.create("http://127.0.0.1:" + port + "/v1/")) + .invokeSync(ClientOperation.GET, VALID_PATH, authorization, null, null, Collections.emptyMap()); + transport(URI.create("http://localhost:" + port + "/")) + .invokeSync(ClientOperation.GET, VALID_PATH, authorization, null, null, Collections.emptyMap()); + + assertEquals(java.util.Arrays.asList("/v1/" + VALID_PATH, "/" + VALID_PATH), receivedPaths); + assertEquals(java.util.Arrays.asList("127.0.0.1:" + port, "localhost:" + port), receivedHosts); + } + + /** Base URIs whose authority holds escapes or an out-of-range port, pointing at the local server: refused, nothing sent. */ + @ParameterizedTest + @ValueSource(strings = {"http://good.example%40127.0.0.1:{port}/v1/", "http://user%3Asecret%40127.0.0.1:{port}/", + "http://127.0.0.1%3A{port}/", "http://localhost%2F127.0.0.1:{port}/", "http://127.0.0.1:{port}00000/", + "http://127.0.0.1:0/", "http://127.0.0.1:99999999999/"}) + void shouldRefuseBaseUrisWithEscapesInTheAuthorityOrAPortOutOfRange(final String template) { + final String baseUri = template.replace("{port}", String.valueOf(server.getAddress().getPort())); + + final CheckoutArgumentException exception = assertThrows(CheckoutArgumentException.class, () -> transport(URI.create(baseUri))); + assertTrue(exception.getMessage().startsWith("Invalid base URI for checkoutApi:"), exception::getMessage); + assertFalse(exception.getMessage().contains("127.0.0.1"), exception::getMessage); + assertTrue(receivedPaths.isEmpty(), "nothing is sent"); + } + + /** + * Pins the existing redirect behaviour, which this change does not alter: a same-host GET redirect + * is followed and the followed request carries no Authorization header. + */ + @Test + void shouldKeepFollowingSameHostGetRedirectsWithoutTheAuthorizationHeader() { + final List targetAuthorization = Collections.synchronizedList(new ArrayList<>()); + server.createContext("/redirect", exchange -> { + exchange.getResponseHeaders().add("Location", "/target"); + exchange.sendResponseHeaders(307, -1); + exchange.close(); + }); + server.createContext("/target", exchange -> { + targetAuthorization.add(String.valueOf(exchange.getRequestHeaders().getFirst("Authorization"))); + final byte[] body = "{}".getBytes(StandardCharsets.UTF_8); + exchange.getResponseHeaders().add("Content-Type", "application/json"); + exchange.sendResponseHeaders(200, body.length); + try (OutputStream out = exchange.getResponseBody()) { + out.write(body); + } + }); + + localTransport().invokeSync(ClientOperation.GET, "redirect", authorization, null, null, Collections.emptyMap()); + + assertEquals(Collections.singletonList("null"), targetAuthorization, "the redirect was followed without credentials"); } @ParameterizedTest @@ -127,6 +226,21 @@ void shouldResolveUnderCustomBaseUris() { "event-types?version=v2#x", "event-types?version=../x", "event-types?version=a?b", + "event-types?version=%zz", + "payments/%2F..%2Fworkflows", + "payments/a%2fb", + "payments/pay_1%2Frefunds", + "payments/%5C..%5Cx", + "payments/a%00b", + "payments/a%0D%0Ab", + "payments/a%7Fb", + "payments/a%zzb", + "payments/a%", + "p\\..\\x", + "payments/a b", + "payments/a:b", + "event-types?version=%2", + "event-types?version=v2%", "a?b/../c", "payments/../x?version=v2", "payments/pay_1#refunds", @@ -135,7 +249,7 @@ void shouldResolveUnderCustomBaseUris() { "mailto:x" }) void shouldRefuseInvalidRequestPaths(final String path) { - assertThrows(CheckoutArgumentException.class, () -> transport(SANDBOX).getRequestUrl(path)); + assertRefused(SANDBOX, path); } @ParameterizedTest @@ -153,6 +267,24 @@ void shouldSendValidPathsAndRefuseDotSegmentsOnEveryOperation(final ClientOperat assertEquals(2, receivedPaths.size(), "no request may reach the server"); } + @Test + void shouldRefuseLongInvalidSegmentsAndQueriesQuickly() { + final String longSegment = repeat("%41a", 50_000) + "!"; + final String longQuery = repeat("a=%41&", 50_000) + "!"; + assertTimeoutPreemptively(Duration.ofSeconds(2), () -> { + assertRefused(SANDBOX, "payments/" + longSegment); + assertRefused(SANDBOX, "payments?" + longQuery); + }); + } + + private static String repeat(final String value, final int times) { + final StringBuilder builder = new StringBuilder(value.length() * times); + for (int i = 0; i < times; i++) { + builder.append(value); + } + return builder.toString(); + } + @Test void shouldEncodeQueryParametersApartFromThePath() { localTransport().invokeSync(ClientOperation.QUERY, "event-types", authorization, null, null, diff --git a/src/test/java/com/checkout/CheckoutSdkBaseUriTest.java b/src/test/java/com/checkout/CheckoutSdkBaseUriTest.java new file mode 100644 index 000000000..c00be5dcd --- /dev/null +++ b/src/test/java/com/checkout/CheckoutSdkBaseUriTest.java @@ -0,0 +1,283 @@ +package com.checkout; + +import static com.checkout.TestHelper.VALID_DEFAULT_SK; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.net.URI; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.stream.Stream; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.junit.jupiter.params.provider.ValueSource; + +/** + * Base URI handling through the public SDK builder, with an HTTP client that records each request + * instead of sending it ({@link RecordingHttpClientBuilder}). + */ +class CheckoutSdkBaseUriTest { + + private static final URI VALID = URI.create("https://proxy.example/"); + private static final String[] SETTINGS = {"checkoutApi", "filesApi", "transfersApi", "balancesApi", "forwardApi", "identityApi"}; + + private final RecordingHttpClientBuilder httpClientBuilder = new RecordingHttpClientBuilder(); + + // Builds without a subdomain on purpose, so the legacy domain switch is needed here. + @SuppressWarnings("deprecation") + private CheckoutApi build(final CustomEnvironment environment) { + return CheckoutSdk.builder().staticKeys() + .secretKey(VALID_DEFAULT_SK) + .environment(environment) + .useLegacyDomain() + .httpClientBuilder(httpClientBuilder) + .recordTelemetry(false) + .build(); + } + + private static CustomEnvironment environment(final String setting, final URI value) { + return CustomEnvironment.builder() + .checkoutApi("checkoutApi".equals(setting) ? value : VALID) + .filesApi("filesApi".equals(setting) ? value : VALID) + .transfersApi("transfersApi".equals(setting) ? value : VALID) + .balancesApi("balancesApi".equals(setting) ? value : VALID) + .forwardApi("forwardApi".equals(setting) ? value : VALID) + .identityApi("identityApi".equals(setting) ? value : VALID) + .oAuthAuthorizationApi(URI.create("https://access.proxy.example/connect/token")) + .sandbox(true) + .build(); + } + + private CheckoutApi buildWithSubdomain(final CustomEnvironment environment) { + return CheckoutSdk.builder().staticKeys() + .secretKey(VALID_DEFAULT_SK) + .environment(environment) + .environmentSubdomain("abc123") + .httpClientBuilder(httpClientBuilder) + .recordTelemetry(false) + .build(); + } + + private String requestUrlWithSubdomainFor(final String baseUri) { + buildWithSubdomain(environment("checkoutApi", URI.create(baseUri))).customersClient().getSync("cus_123"); + assertEquals(1, httpClientBuilder.requests.size()); + return httpClientBuilder.requests.get(0); + } + + private String requestUrlFor(final String baseUri) { + build(environment("checkoutApi", URI.create(baseUri))).customersClient().getSync("cus_123"); + assertEquals(1, httpClientBuilder.requests.size()); + return httpClientBuilder.requests.get(0); + } + + private static Stream invalidBaseUrisPerSetting() { + final String[] invalid = { + "localhost:9000/", "api.example.com/", "/checkout/", "mailto:x@example.com", "ftp://proxy.example/", + "file:///tmp/checkout/", "https:///payments/", "http://:80/", "https://user@/", "https://@/", + "https://proxy.example:abc/", "https://proxy.example:80:90/", + "https://user:secret-value@proxy.example/", "https://user@proxy.example/", "https://%75ser@proxy.example/", + "https://proxy.example/../x/", "https://proxy.example/%2e%2e/x/", "https://proxy.example/%2E/x/", + "https://proxy.example/a/%2e%2E/", "https://proxy.example/./../x/", + "https://proxy.example/..;/x/", "https://proxy.example/%2e%2e;x/y/", "https://proxy.example/.;a/", + "https://proxy.example/a/..;/", "https://proxy.example/a%2Fb/", "https://proxy.example/a%2f..%2fb/", + "https://proxy.example/a%5Cb/", "https://proxy.example/a%00b/", "https://proxy.example/a%0Ab/", + "https://proxy.example/a%7Fb/", + "http://good.example%40127.0.0.1:8080/v1/", "http://user%3Asecret-value%40127.0.0.1/", + "http://127.0.0.1%3A8080/", "https://other.example%2Fgood.example/", "https://proxy%2Eexample/", + "https://%70roxy.example/", "https://proxy.example:0/", "https://proxy.example:00000/", + "https://proxy.example:65536/", "https://proxy.example:99999999999/", + "https://b\u00FCcher.example/", "https://api.te\u202Est/", "https://\u0430pi.example/" + }; + final List arguments = new ArrayList<>(); + for (final String setting : SETTINGS) { + for (final String value : invalid) { + arguments.add(Arguments.of(setting, value)); + } + } + return arguments.stream(); + } + + @ParameterizedTest + @MethodSource("invalidBaseUrisPerSetting") + void shouldRefuseInvalidBaseUrisNamingTheSettingButNotTheValue(final String setting, final String value) { + final CheckoutArgumentException exception = assertThrows(CheckoutArgumentException.class, + () -> build(environment(setting, URI.create(value)))); + + final String message = exception.getMessage(); + assertTrue(message.contains(setting), () -> "the error names the setting: " + message); + for (final String other : SETTINGS) { + if (!other.equals(setting)) { + assertFalse(message.contains(other + " "), () -> "the error names only the invalid setting: " + message); + } + } + assertFalse(message.contains(value), () -> "the error does not echo the value: " + message); + assertFalse(message.contains("secret-value"), () -> "the error does not echo user information: " + message); + assertFalse(message.contains("proxy.example"), () -> "the error does not echo the host: " + message); + assertTrue(httpClientBuilder.requests.isEmpty(), "nothing is sent"); + } + + @Test + void shouldNameTheSettingWhenABaseUriIsMissing() { + final CheckoutArgumentException exception = assertThrows(CheckoutArgumentException.class, + () -> build(environment("filesApi", null))); + assertTrue(exception.getMessage().contains("filesApi"), exception::getMessage); + } + + @ParameterizedTest + @ValueSource(strings = { + "https://proxy.example/|https://proxy.example/customers/cus_123", + "https://proxy.example|https://proxy.example/customers/cus_123", + "https://proxy.example:8443|https://proxy.example:8443/customers/cus_123", + "https://proxy.example:/|https://proxy.example/customers/cus_123", + "https://proxy_host.example/|https://proxy_host.example/customers/cus_123", + "http://checkout_proxy:8080/api/|http://checkout_proxy:8080/api/customers/cus_123", + "https://[::1]:8443/api/|https://[::1]:8443/api/customers/cus_123", + "http://127.1/|http://127.1/customers/cus_123", + "http://localhost.example.net/|http://localhost.example.net/customers/cus_123", + "https://proxy.example/checkout/|https://proxy.example/checkout/customers/cus_123", + "https://proxy.example/a/../b/|https://proxy.example/b/customers/cus_123", + "https://proxy.example/a/..|https://proxy.example/customers/cus_123", + "https://proxy.example//|https://proxy.example/customers/cus_123", + "https://proxy.example/...v1/|https://proxy.example/...v1/customers/cus_123", + "https://proxy.example/v1;a=b/|https://proxy.example/v1;a=b/customers/cus_123", + "https://proxy.example/...;x/|https://proxy.example/...;x/customers/cus_123", + "https://proxy.example/a%20b/|https://proxy.example/a%20b/customers/cus_123", + "https://proxy.example:1/|https://proxy.example:1/customers/cus_123", + "https://proxy.example:65535/|https://proxy.example:65535/customers/cus_123", + "https://proxy.example:08443/|https://proxy.example:8443/customers/cus_123" + }) + void shouldSendRequestsUnderValidBaseUris(final String baseAndExpected) { + final String[] parts = baseAndExpected.split("\\|"); + assertEquals(parts[1], requestUrlFor(parts[0])); + } + + /** The base directory (the path up to the last "/") is kept, so without a trailing slash the last segment is replaced. */ + @Test + void shouldReplaceTheLastBasePathSegmentWhenThereIsNoTrailingSlash() { + assertEquals("https://proxy.example/customers/cus_123", requestUrlFor("https://proxy.example/checkout")); + } + + @ParameterizedTest + @ValueSource(strings = {"a/b@example.com", "a\\b@example.com", "..", "cus_1\r\nX: y"}) + void shouldRefuseCustomerIdentifiersThatAreNotOnePathSegment(final String identifier) { + final CheckoutApi checkoutApi = build(environment("checkoutApi", VALID)); + + assertThrows(CheckoutArgumentException.class, () -> checkoutApi.customersClient().getSync(identifier)); + assertTrue(httpClientBuilder.requests.isEmpty(), "nothing is sent"); + } + + @Test + void shouldSendCustomerEmailsAsOnePathSegment() { + build(environment("checkoutApi", VALID)).customersClient().getSync("a+b@example.com"); + + assertEquals(Collections.singletonList("https://proxy.example/customers/a%2Bb%40example.com"), httpClientBuilder.requests); + } + + private static Stream invalidBaseUrisWithSubdomain() { + return Stream.of( + "https://user:secret-value@proxy.example/", "https://user@proxy.example/", "https://[::1]/", + "https://[::1]:8443/api/", "http://127.0.0.1:8080/", "http://127.1/", "https://proxy.example/a/%2e%2e/b/", + "https://proxy.example/a%2Fb/", "https://proxy.example/..;/x/", "https://proxy.example/../x/", + "http://:80/", "https://@/", "localhost:9000/", "/checkout/", "ftp://proxy.example/", + "https://u%3Ap%40good.example/", "http://0x7f000001/", "http://%31%32%37.0.0.1/", "http://2130706433/", + "http://017700000001/", "http://proxy.0x7f/", "http://proxy.example.123/", "https://proxy.example:0/", + "https://proxy.example:65536/", "https://api.te\u202Est/", "https://\u0430pi.example/", + "https://.example.com/", "https://example..com/", "https://-x.example.com/", "https://x-.example.com/", + "https://proxy.example../", "https://proxy.ex\u00E1mple/"); + } + + @ParameterizedTest + @MethodSource("invalidBaseUrisWithSubdomain") + void shouldRefuseInvalidBaseUrisWithASubdomainNamingTheSettingButNotTheValue(final String value) { + final CheckoutArgumentException exception = assertThrows(CheckoutArgumentException.class, + () -> buildWithSubdomain(environment("checkoutApi", URI.create(value)))); + + final String message = exception.getMessage(); + assertTrue(message.contains("checkoutApi"), () -> "the error names the setting: " + message); + assertFalse(message.contains(value), () -> "the error does not echo the value: " + message); + assertFalse(message.contains("secret-value"), () -> "the error does not echo user information: " + message); + assertFalse(message.contains("proxy.example") || message.contains("::1") || message.contains("127.") + || message.contains("good.example") || message.contains("0x7f"), + () -> "the error does not echo the host: " + message); + assertTrue(httpClientBuilder.requests.isEmpty(), "nothing is sent"); + } + + @Test + void shouldNameTheSettingWhenTheCheckoutApiIsMissingWithASubdomain() { + final CheckoutArgumentException exception = assertThrows(CheckoutArgumentException.class, + () -> buildWithSubdomain(environment("checkoutApi", null))); + assertTrue(exception.getMessage().contains("checkoutApi"), exception::getMessage); + } + + @ParameterizedTest + @ValueSource(strings = { + "https://proxy.example/|https://abc123.proxy.example/customers/cus_123", + "https://proxy.example|https://abc123.proxy.example/customers/cus_123", + "https://my_host.example/|https://abc123.my_host.example/customers/cus_123", + "http://checkout_proxy:8080/api/|http://abc123.checkout_proxy:8080/api/customers/cus_123", + "https://proxy.example/a%20b/|https://abc123.proxy.example/a%20b/customers/cus_123", + "https://proxy.example/a/../b/|https://abc123.proxy.example/b/customers/cus_123", + "https://api.sandbox.checkout.com/|https://abc123.api.sandbox.checkout.com/customers/cus_123", + "http://localhost:8080/|http://abc123.localhost:8080/customers/cus_123", + "https://proxy.example.:8443/|https://abc123.proxy.example.:8443/customers/cus_123", + "https://proxy.x0/|https://abc123.proxy.x0/customers/cus_123" + }) + void shouldSendRequestsUnderTheSubdomainOfValidBaseUris(final String baseAndExpected) { + final String[] parts = baseAndExpected.split("\\|"); + assertEquals(parts[1], requestUrlWithSubdomainFor(parts[0])); + } + + @Test + void shouldAddTheSubdomainToTheAuthorizationUriWithoutDecodingIt() { + final CustomEnvironment environment = CustomEnvironment.builder() + .checkoutApi(VALID) + .oAuthAuthorizationApi(URI.create("https://my_host.example/a%2Fb/connect/token?x=%41")) + .build(); + + assertEquals("https://abc123.my_host.example/a%2Fb/connect/token?x=%41", + 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", + "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"}) + void shouldRefuseAuthorizationUrisThatCannotTakeASubdomainWithoutEchoingThem(final String value) { + final CustomEnvironment environment = CustomEnvironment.builder() + .checkoutApi(VALID) + .oAuthAuthorizationApi(URI.create(value)) + .build(); + + final CheckoutArgumentException exception = assertThrows(CheckoutArgumentException.class, + () -> new EnvironmentSubdomain(environment, "abc123")); + assertTrue(exception.getMessage().contains("oAuthAuthorizationApi"), exception::getMessage); + assertFalse(exception.getMessage().contains(value), exception::getMessage); + } + + @Test + void shouldNameTheSettingWhenTheAuthorizationUriIsMissingWithASubdomain() { + final CustomEnvironment environment = CustomEnvironment.builder().checkoutApi(VALID).build(); + + final CheckoutArgumentException exception = assertThrows(CheckoutArgumentException.class, + () -> new EnvironmentSubdomain(environment, "abc123")); + assertTrue(exception.getMessage().contains("oAuthAuthorizationApi"), exception::getMessage); + } +} diff --git a/src/test/java/com/checkout/RecordingHttpClientBuilder.java b/src/test/java/com/checkout/RecordingHttpClientBuilder.java new file mode 100644 index 000000000..e98e1f8a6 --- /dev/null +++ b/src/test/java/com/checkout/RecordingHttpClientBuilder.java @@ -0,0 +1,72 @@ +package com.checkout; + +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.apache.http.HttpHost; +import org.apache.http.HttpRequest; +import org.apache.http.HttpVersion; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpUriRequest; +import org.apache.http.conn.ClientConnectionManager; +import org.apache.http.entity.ContentType; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClientBuilder; +import org.apache.http.message.BasicHttpResponse; +import org.apache.http.message.BasicStatusLine; +import org.apache.http.params.HttpParams; +import org.apache.http.protocol.HttpContext; + +/** + * HTTP client builder whose client records the URI of every request and answers 200 with an empty + * JSON object; nothing leaves the process. + */ +final class RecordingHttpClientBuilder extends HttpClientBuilder { + + final List requests = Collections.synchronizedList(new ArrayList<>()); + + @Override + public CloseableHttpClient build() { + return new CloseableHttpClient() { + @Override + protected CloseableHttpResponse doExecute(final HttpHost target, final HttpRequest request, final HttpContext context) { + requests.add(((HttpUriRequest) request).getURI().toString()); + final StubResponse response = new StubResponse(); + response.setEntity(new StringEntity("{}", ContentType.APPLICATION_JSON.withCharset(StandardCharsets.UTF_8))); + return response; + } + + @Override + public void close() { + // nothing to release + } + + @Override + @SuppressWarnings("deprecation") + public HttpParams getParams() { + throw new UnsupportedOperationException(); + } + + @Override + @SuppressWarnings("deprecation") + public ClientConnectionManager getConnectionManager() { + throw new UnsupportedOperationException(); + } + }; + } + + private static final class StubResponse extends BasicHttpResponse implements CloseableHttpResponse { + + private StubResponse() { + super(new BasicStatusLine(HttpVersion.HTTP_1_1, 200, "OK")); + } + + @Override + public void close() { + // nothing to release + } + } +} diff --git a/src/test/java/com/checkout/Resilience4jIntegrationTest.java b/src/test/java/com/checkout/Resilience4jIntegrationTest.java index f7d653410..90ea699c8 100644 --- a/src/test/java/com/checkout/Resilience4jIntegrationTest.java +++ b/src/test/java/com/checkout/Resilience4jIntegrationTest.java @@ -41,6 +41,7 @@ void setUp() { final URI baseUri = URI.create("https://api.sandbox.checkout.com/"); transport = new ApacheHttpClientTransport( baseUri, + "checkoutApi", HttpClientBuilder.create(), Executors.newSingleThreadExecutor(), new DefaultTransportConfiguration(), diff --git a/src/test/java/com/checkout/UriCharactersTest.java b/src/test/java/com/checkout/UriCharactersTest.java new file mode 100644 index 000000000..27bf12c67 --- /dev/null +++ b/src/test/java/com/checkout/UriCharactersTest.java @@ -0,0 +1,93 @@ +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 java.util.ArrayList; +import java.util.List; +import java.util.regex.Pattern; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +class UriCharactersTest { + + @ParameterizedTest + @ValueSource(strings = {"pay_123", "a", "%41", "%2e%2E", "A-Z_a.z~0-9", "%ff%00x", "%AF%af"}) + void shouldAcceptEncodedSegments(final String segment) { + assertTrue(UriCharacters.isPercentEncoded(segment, "")); + } + + @ParameterizedTest + @ValueSource(strings = {"", "%", "%4", "%4G", "%G4", "%@0", "a%", "a%4", "%%41", "a b", "a+b", "a*b", "a=b", "a&b", + "a;b", "a:b", "a@b", "a[b", "a`b", "a{b", "a/b", "a\\b", "a?b", "a#b", "café", "١", "A", + "😀", "\ud800", "a\u0000b"}) + void shouldRefuseSegmentsThatAreNotEncoded(final String segment) { + assertFalse(UriCharacters.isPercentEncoded(segment, "")); + } + + @ParameterizedTest + @ValueSource(strings = {"a=1", "a=1&b=2", "q=%20x", "a*b+c", "&&", "="}) + void shouldAcceptEncodedQueries(final String query) { + assertTrue(UriCharacters.isPercentEncoded(query, UriCharacters.QUERY_EXTRA)); + } + + @ParameterizedTest + @ValueSource(strings = {"", "a=1 b", "a=%2", "a=1;b", "a=1#f", "a=?", "a=/b", "a=café", "a=@", "a=:"}) + void shouldRefuseQueriesThatAreNotEncoded(final String query) { + assertFalse(UriCharacters.isPercentEncoded(query, UriCharacters.QUERY_EXTRA)); + } + + @Test + void shouldTreatOnlyUnreservedCharactersAsUnreserved() { + for (int c = 0; c < 256; c++) { + final boolean expected = (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') + || "-._~".indexOf(c) >= 0; + assertEquals(expected, UriCharacters.isUnreserved(c), "character " + c); + } + } + + /** + * The validator against the grammar it implements (RFC 3986 terms), written here as a regular + * expression used only as the reference: + * segment = 1*( ALPHA / DIGIT / "-" / "." / "_" / "~" / pct-encoded ), and + * query = 1*( ALPHA / DIGIT / "-" / "." / "_" / "~" / "*" / "+" / "=" / "&" / pct-encoded ), where + * pct-encoded = "%" HEXDIG HEXDIG. Inputs: every char alone, after "%" and before a hex digit, and every + * pair of ASCII chars alone, after "%" and between letters, so the range boundaries ("/", ":", "@", + * "[", "`", "{"), the hex boundaries and surrogates are all covered. + */ + @Test + void shouldMatchTheSegmentAndQueryGrammarOnEveryShortInput() { + final Pattern segmentGrammar = Pattern.compile("(?:[A-Za-z0-9._~-]|%[0-9A-Fa-f]{2})+"); // NOSONAR reference only + final Pattern queryGrammar = Pattern.compile("(?:[A-Za-z0-9._~*+=&-]|%[0-9A-Fa-f]{2})+"); // NOSONAR reference only + final List inputs = new ArrayList<>(); + for (int c = 0; c <= Character.MAX_VALUE; c++) { + inputs.add(String.valueOf((char) c)); + inputs.add("%" + (char) c + "0"); + inputs.add("%0" + (char) c); + } + for (char x = 0; x < 128; x++) { + for (char y = 0; y < 128; y++) { + inputs.add("" + x + y); + inputs.add("%" + x + y); + inputs.add("a%" + x + y + "b"); + } + } + for (final String candidate : inputs) { + assertEquals(segmentGrammar.matcher(candidate).matches(), + UriCharacters.isPercentEncoded(candidate, ""), () -> "segment: " + escape(candidate)); + assertEquals(queryGrammar.matcher(candidate).matches(), + UriCharacters.isPercentEncoded(candidate, UriCharacters.QUERY_EXTRA), () -> "query: " + escape(candidate)); + } + } + + private static String escape(final String value) { + final StringBuilder builder = new StringBuilder(); + for (final char c : value.toCharArray()) { + builder.append(c >= 0x20 && c < 0x7f ? String.valueOf(c) : String.format("\\u%04x", (int) c)); + } + return builder.toString(); + } +}