software.amazon.awssdk.services.sso.DefaultSsoAsyncClient Maven / Gradle / Ivy
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package software.amazon.awssdk.services.sso;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.function.Consumer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import software.amazon.awssdk.annotations.Generated;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.awscore.client.handler.AwsAsyncClientHandler;
import software.amazon.awssdk.awscore.exception.AwsServiceException;
import software.amazon.awssdk.awscore.internal.AwsProtocolMetadata;
import software.amazon.awssdk.awscore.internal.AwsServiceProtocol;
import software.amazon.awssdk.awscore.retry.AwsRetryStrategy;
import software.amazon.awssdk.core.RequestOverrideConfiguration;
import software.amazon.awssdk.core.SdkPlugin;
import software.amazon.awssdk.core.SdkRequest;
import software.amazon.awssdk.core.client.config.ClientOverrideConfiguration;
import software.amazon.awssdk.core.client.config.SdkClientConfiguration;
import software.amazon.awssdk.core.client.config.SdkClientOption;
import software.amazon.awssdk.core.client.handler.AsyncClientHandler;
import software.amazon.awssdk.core.client.handler.ClientExecutionParams;
import software.amazon.awssdk.core.http.HttpResponseHandler;
import software.amazon.awssdk.core.metrics.CoreMetric;
import software.amazon.awssdk.core.retry.RetryMode;
import software.amazon.awssdk.metrics.MetricCollector;
import software.amazon.awssdk.metrics.MetricPublisher;
import software.amazon.awssdk.metrics.NoOpMetricCollector;
import software.amazon.awssdk.protocols.core.ExceptionMetadata;
import software.amazon.awssdk.protocols.json.AwsJsonProtocol;
import software.amazon.awssdk.protocols.json.AwsJsonProtocolFactory;
import software.amazon.awssdk.protocols.json.BaseAwsJsonProtocolFactory;
import software.amazon.awssdk.protocols.json.JsonOperationMetadata;
import software.amazon.awssdk.retries.api.RetryStrategy;
import software.amazon.awssdk.services.sso.internal.SsoServiceClientConfigurationBuilder;
import software.amazon.awssdk.services.sso.model.GetRoleCredentialsRequest;
import software.amazon.awssdk.services.sso.model.GetRoleCredentialsResponse;
import software.amazon.awssdk.services.sso.model.InvalidRequestException;
import software.amazon.awssdk.services.sso.model.ListAccountRolesRequest;
import software.amazon.awssdk.services.sso.model.ListAccountRolesResponse;
import software.amazon.awssdk.services.sso.model.ListAccountsRequest;
import software.amazon.awssdk.services.sso.model.ListAccountsResponse;
import software.amazon.awssdk.services.sso.model.LogoutRequest;
import software.amazon.awssdk.services.sso.model.LogoutResponse;
import software.amazon.awssdk.services.sso.model.ResourceNotFoundException;
import software.amazon.awssdk.services.sso.model.SsoException;
import software.amazon.awssdk.services.sso.model.TooManyRequestsException;
import software.amazon.awssdk.services.sso.model.UnauthorizedException;
import software.amazon.awssdk.services.sso.transform.GetRoleCredentialsRequestMarshaller;
import software.amazon.awssdk.services.sso.transform.ListAccountRolesRequestMarshaller;
import software.amazon.awssdk.services.sso.transform.ListAccountsRequestMarshaller;
import software.amazon.awssdk.services.sso.transform.LogoutRequestMarshaller;
import software.amazon.awssdk.utils.CompletableFutureUtils;
/**
* Internal implementation of {@link SsoAsyncClient}.
*
* @see SsoAsyncClient#builder()
*/
@Generated("software.amazon.awssdk:codegen")
@SdkInternalApi
final class DefaultSsoAsyncClient implements SsoAsyncClient {
private static final Logger log = LoggerFactory.getLogger(DefaultSsoAsyncClient.class);
private static final AwsProtocolMetadata protocolMetadata = AwsProtocolMetadata.builder()
.serviceProtocol(AwsServiceProtocol.REST_JSON).build();
private final AsyncClientHandler clientHandler;
private final AwsJsonProtocolFactory protocolFactory;
private final SdkClientConfiguration clientConfiguration;
protected DefaultSsoAsyncClient(SdkClientConfiguration clientConfiguration) {
this.clientHandler = new AwsAsyncClientHandler(clientConfiguration);
this.clientConfiguration = clientConfiguration.toBuilder().option(SdkClientOption.SDK_CLIENT, this).build();
this.protocolFactory = init(AwsJsonProtocolFactory.builder()).build();
}
/**
*
* Returns the STS short-term credentials for a given role name that is assigned to the user.
*
*
* @param getRoleCredentialsRequest
* @return A Java Future containing the result of the GetRoleCredentials operation returned by the service.
* The CompletableFuture returned by this method can be completed exceptionally with the following
* exceptions. The exception returned is wrapped with CompletionException, so you need to invoke
* {@link Throwable#getCause} to retrieve the underlying exception.
*
* - InvalidRequestException Indicates that a problem occurred with the input to the request. For example,
* a required parameter might be missing or out of range.
* - UnauthorizedException Indicates that the request is not authorized. This can happen due to an invalid
* access token in the request.
* - TooManyRequestsException Indicates that the request is being made too frequently and is more than
* what the server can handle.
* - ResourceNotFoundException The specified resource doesn't exist.
* - SdkException Base class for all exceptions that can be thrown by the SDK (both service and client).
* Can be used for catch all scenarios.
* - SdkClientException If any client side error occurs such as an IO related failure, failure to get
* credentials, etc.
* - SsoException Base class for all service exceptions. Unknown exceptions will be thrown as an instance
* of this type.
*
* @sample SsoAsyncClient.GetRoleCredentials
* @see AWS API
* Documentation
*/
@Override
public CompletableFuture getRoleCredentials(GetRoleCredentialsRequest getRoleCredentialsRequest) {
SdkClientConfiguration clientConfiguration = updateSdkClientConfiguration(getRoleCredentialsRequest,
this.clientConfiguration);
List metricPublishers = resolveMetricPublishers(clientConfiguration, getRoleCredentialsRequest
.overrideConfiguration().orElse(null));
MetricCollector apiCallMetricCollector = metricPublishers.isEmpty() ? NoOpMetricCollector.create() : MetricCollector
.create("ApiCall");
try {
apiCallMetricCollector.reportMetric(CoreMetric.SERVICE_ID, "SSO");
apiCallMetricCollector.reportMetric(CoreMetric.OPERATION_NAME, "GetRoleCredentials");
JsonOperationMetadata operationMetadata = JsonOperationMetadata.builder().hasStreamingSuccessResponse(false)
.isPayloadJson(true).build();
HttpResponseHandler responseHandler = protocolFactory.createResponseHandler(
operationMetadata, GetRoleCredentialsResponse::builder);
HttpResponseHandler errorResponseHandler = createErrorResponseHandler(protocolFactory,
operationMetadata);
CompletableFuture executeFuture = clientHandler
.execute(new ClientExecutionParams()
.withOperationName("GetRoleCredentials").withProtocolMetadata(protocolMetadata)
.withMarshaller(new GetRoleCredentialsRequestMarshaller(protocolFactory))
.withResponseHandler(responseHandler).withErrorResponseHandler(errorResponseHandler)
.withRequestConfiguration(clientConfiguration).withMetricCollector(apiCallMetricCollector)
.withInput(getRoleCredentialsRequest));
CompletableFuture whenCompleted = executeFuture.whenComplete((r, e) -> {
metricPublishers.forEach(p -> p.publish(apiCallMetricCollector.collect()));
});
executeFuture = CompletableFutureUtils.forwardExceptionTo(whenCompleted, executeFuture);
return executeFuture;
} catch (Throwable t) {
metricPublishers.forEach(p -> p.publish(apiCallMetricCollector.collect()));
return CompletableFutureUtils.failedFuture(t);
}
}
/**
*
* Lists all roles that are assigned to the user for a given AWS account.
*
*
* @param listAccountRolesRequest
* @return A Java Future containing the result of the ListAccountRoles operation returned by the service.
* The CompletableFuture returned by this method can be completed exceptionally with the following
* exceptions. The exception returned is wrapped with CompletionException, so you need to invoke
* {@link Throwable#getCause} to retrieve the underlying exception.
*
* - InvalidRequestException Indicates that a problem occurred with the input to the request. For example,
* a required parameter might be missing or out of range.
* - UnauthorizedException Indicates that the request is not authorized. This can happen due to an invalid
* access token in the request.
* - TooManyRequestsException Indicates that the request is being made too frequently and is more than
* what the server can handle.
* - ResourceNotFoundException The specified resource doesn't exist.
* - SdkException Base class for all exceptions that can be thrown by the SDK (both service and client).
* Can be used for catch all scenarios.
* - SdkClientException If any client side error occurs such as an IO related failure, failure to get
* credentials, etc.
* - SsoException Base class for all service exceptions. Unknown exceptions will be thrown as an instance
* of this type.
*
* @sample SsoAsyncClient.ListAccountRoles
* @see AWS API
* Documentation
*/
@Override
public CompletableFuture listAccountRoles(ListAccountRolesRequest listAccountRolesRequest) {
SdkClientConfiguration clientConfiguration = updateSdkClientConfiguration(listAccountRolesRequest,
this.clientConfiguration);
List metricPublishers = resolveMetricPublishers(clientConfiguration, listAccountRolesRequest
.overrideConfiguration().orElse(null));
MetricCollector apiCallMetricCollector = metricPublishers.isEmpty() ? NoOpMetricCollector.create() : MetricCollector
.create("ApiCall");
try {
apiCallMetricCollector.reportMetric(CoreMetric.SERVICE_ID, "SSO");
apiCallMetricCollector.reportMetric(CoreMetric.OPERATION_NAME, "ListAccountRoles");
JsonOperationMetadata operationMetadata = JsonOperationMetadata.builder().hasStreamingSuccessResponse(false)
.isPayloadJson(true).build();
HttpResponseHandler responseHandler = protocolFactory.createResponseHandler(
operationMetadata, ListAccountRolesResponse::builder);
HttpResponseHandler errorResponseHandler = createErrorResponseHandler(protocolFactory,
operationMetadata);
CompletableFuture executeFuture = clientHandler
.execute(new ClientExecutionParams()
.withOperationName("ListAccountRoles").withProtocolMetadata(protocolMetadata)
.withMarshaller(new ListAccountRolesRequestMarshaller(protocolFactory))
.withResponseHandler(responseHandler).withErrorResponseHandler(errorResponseHandler)
.withRequestConfiguration(clientConfiguration).withMetricCollector(apiCallMetricCollector)
.withInput(listAccountRolesRequest));
CompletableFuture whenCompleted = executeFuture.whenComplete((r, e) -> {
metricPublishers.forEach(p -> p.publish(apiCallMetricCollector.collect()));
});
executeFuture = CompletableFutureUtils.forwardExceptionTo(whenCompleted, executeFuture);
return executeFuture;
} catch (Throwable t) {
metricPublishers.forEach(p -> p.publish(apiCallMetricCollector.collect()));
return CompletableFutureUtils.failedFuture(t);
}
}
/**
*
* Lists all AWS accounts assigned to the user. These AWS accounts are assigned by the administrator of the account.
* For more information, see Assign User
* Access in the IAM Identity Center User Guide. This operation returns a paginated response.
*
*
* @param listAccountsRequest
* @return A Java Future containing the result of the ListAccounts operation returned by the service.
* The CompletableFuture returned by this method can be completed exceptionally with the following
* exceptions. The exception returned is wrapped with CompletionException, so you need to invoke
* {@link Throwable#getCause} to retrieve the underlying exception.
*
* - InvalidRequestException Indicates that a problem occurred with the input to the request. For example,
* a required parameter might be missing or out of range.
* - UnauthorizedException Indicates that the request is not authorized. This can happen due to an invalid
* access token in the request.
* - TooManyRequestsException Indicates that the request is being made too frequently and is more than
* what the server can handle.
* - ResourceNotFoundException The specified resource doesn't exist.
* - SdkException Base class for all exceptions that can be thrown by the SDK (both service and client).
* Can be used for catch all scenarios.
* - SdkClientException If any client side error occurs such as an IO related failure, failure to get
* credentials, etc.
* - SsoException Base class for all service exceptions. Unknown exceptions will be thrown as an instance
* of this type.
*
* @sample SsoAsyncClient.ListAccounts
* @see AWS API
* Documentation
*/
@Override
public CompletableFuture listAccounts(ListAccountsRequest listAccountsRequest) {
SdkClientConfiguration clientConfiguration = updateSdkClientConfiguration(listAccountsRequest, this.clientConfiguration);
List metricPublishers = resolveMetricPublishers(clientConfiguration, listAccountsRequest
.overrideConfiguration().orElse(null));
MetricCollector apiCallMetricCollector = metricPublishers.isEmpty() ? NoOpMetricCollector.create() : MetricCollector
.create("ApiCall");
try {
apiCallMetricCollector.reportMetric(CoreMetric.SERVICE_ID, "SSO");
apiCallMetricCollector.reportMetric(CoreMetric.OPERATION_NAME, "ListAccounts");
JsonOperationMetadata operationMetadata = JsonOperationMetadata.builder().hasStreamingSuccessResponse(false)
.isPayloadJson(true).build();
HttpResponseHandler responseHandler = protocolFactory.createResponseHandler(operationMetadata,
ListAccountsResponse::builder);
HttpResponseHandler errorResponseHandler = createErrorResponseHandler(protocolFactory,
operationMetadata);
CompletableFuture executeFuture = clientHandler
.execute(new ClientExecutionParams()
.withOperationName("ListAccounts").withProtocolMetadata(protocolMetadata)
.withMarshaller(new ListAccountsRequestMarshaller(protocolFactory))
.withResponseHandler(responseHandler).withErrorResponseHandler(errorResponseHandler)
.withRequestConfiguration(clientConfiguration).withMetricCollector(apiCallMetricCollector)
.withInput(listAccountsRequest));
CompletableFuture whenCompleted = executeFuture.whenComplete((r, e) -> {
metricPublishers.forEach(p -> p.publish(apiCallMetricCollector.collect()));
});
executeFuture = CompletableFutureUtils.forwardExceptionTo(whenCompleted, executeFuture);
return executeFuture;
} catch (Throwable t) {
metricPublishers.forEach(p -> p.publish(apiCallMetricCollector.collect()));
return CompletableFutureUtils.failedFuture(t);
}
}
/**
*
* Removes the locally stored SSO tokens from the client-side cache and sends an API call to the IAM Identity Center
* service to invalidate the corresponding server-side IAM Identity Center sign in session.
*
*
*
* If a user uses IAM Identity Center to access the AWS CLI, the user’s IAM Identity Center sign in session is used
* to obtain an IAM session, as specified in the corresponding IAM Identity Center permission set. More
* specifically, IAM Identity Center assumes an IAM role in the target account on behalf of the user, and the
* corresponding temporary AWS credentials are returned to the client.
*
*
* After user logout, any existing IAM role sessions that were created by using IAM Identity Center permission sets
* continue based on the duration configured in the permission set. For more information, see User authentications in the
* IAM Identity Center User Guide.
*
*
*
* @param logoutRequest
* @return A Java Future containing the result of the Logout operation returned by the service.
* The CompletableFuture returned by this method can be completed exceptionally with the following
* exceptions. The exception returned is wrapped with CompletionException, so you need to invoke
* {@link Throwable#getCause} to retrieve the underlying exception.
*
* - InvalidRequestException Indicates that a problem occurred with the input to the request. For example,
* a required parameter might be missing or out of range.
* - UnauthorizedException Indicates that the request is not authorized. This can happen due to an invalid
* access token in the request.
* - TooManyRequestsException Indicates that the request is being made too frequently and is more than
* what the server can handle.
* - SdkException Base class for all exceptions that can be thrown by the SDK (both service and client).
* Can be used for catch all scenarios.
* - SdkClientException If any client side error occurs such as an IO related failure, failure to get
* credentials, etc.
* - SsoException Base class for all service exceptions. Unknown exceptions will be thrown as an instance
* of this type.
*
* @sample SsoAsyncClient.Logout
* @see AWS API
* Documentation
*/
@Override
public CompletableFuture logout(LogoutRequest logoutRequest) {
SdkClientConfiguration clientConfiguration = updateSdkClientConfiguration(logoutRequest, this.clientConfiguration);
List metricPublishers = resolveMetricPublishers(clientConfiguration, logoutRequest
.overrideConfiguration().orElse(null));
MetricCollector apiCallMetricCollector = metricPublishers.isEmpty() ? NoOpMetricCollector.create() : MetricCollector
.create("ApiCall");
try {
apiCallMetricCollector.reportMetric(CoreMetric.SERVICE_ID, "SSO");
apiCallMetricCollector.reportMetric(CoreMetric.OPERATION_NAME, "Logout");
JsonOperationMetadata operationMetadata = JsonOperationMetadata.builder().hasStreamingSuccessResponse(false)
.isPayloadJson(true).build();
HttpResponseHandler responseHandler = protocolFactory.createResponseHandler(operationMetadata,
LogoutResponse::builder);
HttpResponseHandler errorResponseHandler = createErrorResponseHandler(protocolFactory,
operationMetadata);
CompletableFuture executeFuture = clientHandler
.execute(new ClientExecutionParams().withOperationName("Logout")
.withProtocolMetadata(protocolMetadata).withMarshaller(new LogoutRequestMarshaller(protocolFactory))
.withResponseHandler(responseHandler).withErrorResponseHandler(errorResponseHandler)
.withRequestConfiguration(clientConfiguration).withMetricCollector(apiCallMetricCollector)
.withInput(logoutRequest));
CompletableFuture whenCompleted = executeFuture.whenComplete((r, e) -> {
metricPublishers.forEach(p -> p.publish(apiCallMetricCollector.collect()));
});
executeFuture = CompletableFutureUtils.forwardExceptionTo(whenCompleted, executeFuture);
return executeFuture;
} catch (Throwable t) {
metricPublishers.forEach(p -> p.publish(apiCallMetricCollector.collect()));
return CompletableFutureUtils.failedFuture(t);
}
}
@Override
public final SsoServiceClientConfiguration serviceClientConfiguration() {
return new SsoServiceClientConfigurationBuilder(this.clientConfiguration.toBuilder()).build();
}
@Override
public final String serviceName() {
return SERVICE_NAME;
}
private > T init(T builder) {
return builder
.clientConfiguration(clientConfiguration)
.defaultServiceExceptionSupplier(SsoException::builder)
.protocol(AwsJsonProtocol.REST_JSON)
.protocolVersion("1.1")
.registerModeledException(
ExceptionMetadata.builder().errorCode("TooManyRequestsException")
.exceptionBuilderSupplier(TooManyRequestsException::builder).httpStatusCode(429).build())
.registerModeledException(
ExceptionMetadata.builder().errorCode("UnauthorizedException")
.exceptionBuilderSupplier(UnauthorizedException::builder).httpStatusCode(401).build())
.registerModeledException(
ExceptionMetadata.builder().errorCode("InvalidRequestException")
.exceptionBuilderSupplier(InvalidRequestException::builder).httpStatusCode(400).build())
.registerModeledException(
ExceptionMetadata.builder().errorCode("ResourceNotFoundException")
.exceptionBuilderSupplier(ResourceNotFoundException::builder).httpStatusCode(404).build());
}
private static List resolveMetricPublishers(SdkClientConfiguration clientConfiguration,
RequestOverrideConfiguration requestOverrideConfiguration) {
List publishers = null;
if (requestOverrideConfiguration != null) {
publishers = requestOverrideConfiguration.metricPublishers();
}
if (publishers == null || publishers.isEmpty()) {
publishers = clientConfiguration.option(SdkClientOption.METRIC_PUBLISHERS);
}
if (publishers == null) {
publishers = Collections.emptyList();
}
return publishers;
}
private void updateRetryStrategyClientConfiguration(SdkClientConfiguration.Builder configuration) {
ClientOverrideConfiguration.Builder builder = configuration.asOverrideConfigurationBuilder();
RetryMode retryMode = builder.retryMode();
if (retryMode != null) {
configuration.option(SdkClientOption.RETRY_STRATEGY, AwsRetryStrategy.forRetryMode(retryMode));
} else {
Consumer> configurator = builder.retryStrategyConfigurator();
if (configurator != null) {
RetryStrategy.Builder, ?> defaultBuilder = AwsRetryStrategy.defaultRetryStrategy().toBuilder();
configurator.accept(defaultBuilder);
configuration.option(SdkClientOption.RETRY_STRATEGY, defaultBuilder.build());
} else {
RetryStrategy retryStrategy = builder.retryStrategy();
if (retryStrategy != null) {
configuration.option(SdkClientOption.RETRY_STRATEGY, retryStrategy);
}
}
}
configuration.option(SdkClientOption.CONFIGURED_RETRY_MODE, null);
configuration.option(SdkClientOption.CONFIGURED_RETRY_STRATEGY, null);
configuration.option(SdkClientOption.CONFIGURED_RETRY_CONFIGURATOR, null);
}
private SdkClientConfiguration updateSdkClientConfiguration(SdkRequest request, SdkClientConfiguration clientConfiguration) {
List plugins = request.overrideConfiguration().map(c -> c.plugins()).orElse(Collections.emptyList());
SdkClientConfiguration.Builder configuration = clientConfiguration.toBuilder();
if (plugins.isEmpty()) {
return configuration.build();
}
SsoServiceClientConfigurationBuilder serviceConfigBuilder = new SsoServiceClientConfigurationBuilder(configuration);
for (SdkPlugin plugin : plugins) {
plugin.configureClient(serviceConfigBuilder);
}
updateRetryStrategyClientConfiguration(configuration);
return configuration.build();
}
private HttpResponseHandler createErrorResponseHandler(BaseAwsJsonProtocolFactory protocolFactory,
JsonOperationMetadata operationMetadata) {
return protocolFactory.createErrorResponseHandler(operationMetadata);
}
@Override
public void close() {
clientHandler.close();
}
}