index int64 0 0 | repo_id stringlengths 9 205 | file_path stringlengths 31 246 | content stringlengths 1 12.2M | __index_level_0__ int64 0 10k |
|---|---|---|---|---|
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/token | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/token/internal/LazyTokenProvider.java | /*
* 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.auth.token.internal;
import java.util.function.Supplier;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.auth.token.credentials.SdkToken;
import software.amazon.awssdk.auth.token.credentials.SdkTokenProvider;
import software.amazon.awssdk.utils.IoUtils;
import software.amazon.awssdk.utils.Lazy;
import software.amazon.awssdk.utils.SdkAutoCloseable;
import software.amazon.awssdk.utils.ToString;
/**
* A wrapper for {@link SdkTokenProvider} that defers creation of the underlying provider until the first time the
* {@link SdkTokenProvider#resolveToken()} method is invoked.
*/
@SdkInternalApi
public class LazyTokenProvider implements SdkTokenProvider, SdkAutoCloseable {
private final Lazy<SdkTokenProvider> delegate;
public LazyTokenProvider(Supplier<SdkTokenProvider> delegateConstructor) {
this.delegate = new Lazy<>(delegateConstructor);
}
public static LazyTokenProvider create(Supplier<SdkTokenProvider> delegateConstructor) {
return new LazyTokenProvider(delegateConstructor);
}
@Override
public SdkToken resolveToken() {
return delegate.getValue().resolveToken();
}
@Override
public void close() {
IoUtils.closeIfCloseable(delegate, null);
}
@Override
public String toString() {
return ToString.builder("LazyTokenProvider")
.add("delegate", delegate)
.build();
}
}
| 1,700 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/token | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/token/credentials/SdkTokenProvider.java | /*
* 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.auth.token.credentials;
import java.util.concurrent.CompletableFuture;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.identity.spi.IdentityProvider;
import software.amazon.awssdk.identity.spi.ResolveIdentityRequest;
import software.amazon.awssdk.identity.spi.TokenIdentity;
/**
* Interface for loading {@link SdkToken} that are used for authentication.
*
*/
@FunctionalInterface
@SdkPublicApi
public interface SdkTokenProvider extends IdentityProvider<TokenIdentity> {
/**
* Returns an {@link SdkToken} that can be used to authorize a request. Each implementation of SdkTokenProvider
* can choose its own strategy for loading token. For example, an implementation might load token from an existing
* key management system, or load new token when token is refreshed.
*
*
* @return AwsToken which the caller can use to authorize an AWS request using token authorization for a request.
*/
SdkToken resolveToken();
@Override
default Class<TokenIdentity> identityType() {
return TokenIdentity.class;
}
@Override
default CompletableFuture<TokenIdentity> resolveIdentity(ResolveIdentityRequest request) {
return CompletableFuture.completedFuture(resolveToken());
}
}
| 1,701 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/token | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/token/credentials/SdkTokenProviderFactoryProperties.java | /*
* 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.auth.token.credentials;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.utils.Validate;
@SdkProtectedApi
public class SdkTokenProviderFactoryProperties {
private final String startUrl;
private final String region;
private SdkTokenProviderFactoryProperties(BuilderImpl builder) {
Validate.paramNotNull(builder.startUrl, "startUrl");
Validate.paramNotNull(builder.region, "region");
this.startUrl = builder.startUrl;
this.region = builder.region;
}
public String startUrl() {
return startUrl;
}
public String region() {
return region;
}
public static Builder builder() {
return new BuilderImpl();
}
public interface Builder {
Builder startUrl(String startUrl);
Builder region(String region);
SdkTokenProviderFactoryProperties build();
}
private static class BuilderImpl implements Builder {
private String startUrl;
private String region;
@Override
public Builder startUrl(String startUrl) {
this.startUrl = startUrl;
return this;
}
@Override
public Builder region(String region) {
this.region = region;
return this;
}
@Override
public SdkTokenProviderFactoryProperties build() {
return new SdkTokenProviderFactoryProperties(this);
}
}
}
| 1,702 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/token | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/token/credentials/ChildProfileTokenProviderFactory.java | /*
* 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.auth.token.credentials;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.profiles.Profile;
import software.amazon.awssdk.profiles.ProfileFile;
/**
* A factory for {@link SdkTokenProvider} that are derived from properties as defined in he given profile.
*
* Currently, this is used to allow a {@link Profile} configured with start_url and sso_region to configure a token
* provider via the 'software.amazon.awssdk.services.ssooidc.internal.SsooidcTokenProviderFactory', assuming ssooidc is on the
* classpath.
*/
@FunctionalInterface
@SdkProtectedApi
public interface ChildProfileTokenProviderFactory {
/**
* Create a token provider for the provided profile.
*
* @param profileFile The ProfileFile from which the Profile was derived.
* @param profile The profile that should be used to load the configuration necessary to create the token provider.
* @return The token provider with the properties derived from the source profile.
*/
SdkTokenProvider create(ProfileFile profileFile, Profile profile);
}
| 1,703 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/token | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/token/credentials/StaticTokenProvider.java | /*
* 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.auth.token.credentials;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.Validate;
/**
* An implementation of {@link SdkTokenProvider} that returns a set implementation of {@link SdkToken}.
*/
@SdkPublicApi
public final class StaticTokenProvider implements SdkTokenProvider {
private final SdkToken token;
private StaticTokenProvider(SdkToken token) {
this.token = Validate.notNull(token, "Token must not be null.");
}
/**
* Create a token provider that always returns the provided static token.
*/
public static StaticTokenProvider create(SdkToken token) {
return new StaticTokenProvider(token);
}
@Override
public SdkToken resolveToken() {
return token;
}
@Override
public String toString() {
return ToString.builder("StaticTokenProvider")
.add("token", token)
.build();
}
}
| 1,704 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/token | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/token/credentials/ProfileTokenProvider.java | /*
* 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.auth.token.credentials;
import java.util.Optional;
import java.util.function.Supplier;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.annotations.SdkTestInternalApi;
import software.amazon.awssdk.auth.token.internal.ProfileTokenProviderLoader;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.profiles.ProfileFile;
import software.amazon.awssdk.profiles.ProfileFileSystemSetting;
import software.amazon.awssdk.utils.IoUtils;
import software.amazon.awssdk.utils.SdkAutoCloseable;
import software.amazon.awssdk.utils.ToString;
/**
* Token provider based on AWS configuration profiles. This loads token providers that require {@link ProfileFile} configuration,
* allowing the user to share settings between different tools like the AWS SDK for Java and the AWS CLI.
*
* <p>See http://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html</p>
*
* @see ProfileFile
*/
@SdkPublicApi
public final class ProfileTokenProvider implements SdkTokenProvider, SdkAutoCloseable {
private final SdkTokenProvider tokenProvider;
private final RuntimeException loadException;
private final String profileName;
/**
* @see #builder()
*/
private ProfileTokenProvider(BuilderImpl builder) {
SdkTokenProvider sdkTokenProvider = null;
RuntimeException thrownException = null;
Supplier<ProfileFile> selectedProfileFile = null;
String selectedProfileName = null;
try {
selectedProfileName = Optional.ofNullable(builder.profileName)
.orElseGet(ProfileFileSystemSetting.AWS_PROFILE::getStringValueOrThrow);
// Load the profiles file
selectedProfileFile = Optional.ofNullable(builder.profileFile)
.orElse(builder.defaultProfileFileLoader);
// Load the profile and token provider
sdkTokenProvider = createTokenProvider(selectedProfileFile, selectedProfileName);
} catch (RuntimeException e) {
// If we couldn't load the provider for some reason, save an exception describing why.
thrownException = e;
}
if (thrownException != null) {
this.loadException = thrownException;
this.tokenProvider = null;
this.profileName = null;
} else {
this.loadException = null;
this.tokenProvider = sdkTokenProvider;
this.profileName = selectedProfileName;
}
}
/**
* Create a {@link ProfileTokenProvider} using the {@link ProfileFile#defaultProfileFile()} and default profile name.
* Use {@link #builder()} for defining a custom {@link ProfileTokenProvider}.
*/
public static ProfileTokenProvider create() {
return builder().build();
}
/**
* Create a {@link ProfileTokenProvider} using the given profile name and {@link ProfileFile#defaultProfileFile()}. Use
* {@link #builder()} for defining a custom {@link ProfileTokenProvider}.
*
* @param profileName the name of the profile to use from the {@link ProfileFile#defaultProfileFile()}
*/
public static ProfileTokenProvider create(String profileName) {
return builder().profileName(profileName).build();
}
/**
* Get a builder for creating a custom {@link ProfileTokenProvider}.
*/
public static Builder builder() {
return new BuilderImpl();
}
@Override
public SdkToken resolveToken() {
if (loadException != null) {
throw loadException;
}
return tokenProvider.resolveToken();
}
@Override
public String toString() {
return ToString.builder("ProfileTokenProvider")
.add("profileName", profileName)
.build();
}
@Override
public void close() {
// The delegate provider may be closeable. In this case, we should clean it up when this token provider is closed.
IoUtils.closeIfCloseable(tokenProvider, null);
}
private SdkTokenProvider createTokenProvider(Supplier<ProfileFile> profileFile, String profileName) {
return new ProfileTokenProviderLoader(profileFile, profileName)
.tokenProvider()
.orElseThrow(() -> {
String errorMessage = String.format("Profile file contained no information for " +
"profile '%s'", profileName);
return SdkClientException.builder().message(errorMessage).build();
});
}
/**
* A builder for creating a custom {@link ProfileTokenProvider}.
*/
public interface Builder {
/**
* Define the profile file that should be used by this token provider. By default, the
* {@link ProfileFile#defaultProfileFile()} is used.
*/
Builder profileFile(Supplier<ProfileFile> profileFile);
/**
* Define the name of the profile that should be used by this token provider. By default, the value in
* {@link ProfileFileSystemSetting#AWS_PROFILE} is used.
*/
Builder profileName(String profileName);
/**
* Create a {@link ProfileTokenProvider} using the configuration applied to this builder.
*/
ProfileTokenProvider build();
}
static final class BuilderImpl implements Builder {
private Supplier<ProfileFile> profileFile;
private String profileName;
private Supplier<ProfileFile> defaultProfileFileLoader = ProfileFile::defaultProfileFile;
BuilderImpl() {
}
@Override
public Builder profileFile(Supplier<ProfileFile> profileFile) {
this.profileFile = profileFile;
return this;
}
public void setProfileFile(Supplier<ProfileFile> profileFile) {
profileFile(profileFile);
}
@Override
public Builder profileName(String profileName) {
this.profileName = profileName;
return this;
}
public void setProfileName(String profileName) {
profileName(profileName);
}
@Override
public ProfileTokenProvider build() {
return new ProfileTokenProvider(this);
}
/**
* Override the default configuration file to be used when the customer does not explicitly set
* profileName(profileName);
* {@link #profileFile(Supplier<ProfileFile>)}. Use of this method is only useful for testing the default behavior.
*/
@SdkTestInternalApi
Builder defaultProfileFileLoader(Supplier<ProfileFile> defaultProfileFileLoader) {
this.defaultProfileFileLoader = defaultProfileFileLoader;
return this;
}
}
}
| 1,705 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/token | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/token/credentials/SdkTokenProviderChain.java | /*
* 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.auth.token.credentials;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.auth.credentials.TokenUtils;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.identity.spi.IdentityProvider;
import software.amazon.awssdk.identity.spi.TokenIdentity;
import software.amazon.awssdk.utils.CompletableFutureUtils;
import software.amazon.awssdk.utils.IoUtils;
import software.amazon.awssdk.utils.Logger;
import software.amazon.awssdk.utils.SdkAutoCloseable;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.Validate;
/**
* An {@link SdkTokenProvider} implementation that chains together multiple token providers.
*
* <p>When a caller first requests token from this provider, it calls all the providers in the chain, in the original order
* specified, until one can provide a token, and then returns that token. If all of the token providers in the
* chain have been called, and none of them can provide token, then this class will throw an exception indicated that no
* token is available.</p>
*
* <p>By default, this class will remember the first token provider in the chain that was able to provide tokens, and
* will continue to use that provider when token is requested in the future, instead of traversing the chain each time.
* This behavior can be controlled through the {@link Builder#reuseLastProviderEnabled(Boolean)} method.</p>
*
* <p>This chain implements {@link AutoCloseable}. When closed, it will call the {@link AutoCloseable#close()} on any token
* providers in the chain that need to be closed.</p>
*/
@SdkPublicApi
public final class SdkTokenProviderChain implements SdkTokenProvider, SdkAutoCloseable {
private static final Logger log = Logger.loggerFor(SdkTokenProviderChain.class);
private final List<IdentityProvider<? extends TokenIdentity>> sdkTokenProviders;
private final boolean reuseLastProviderEnabled;
private volatile IdentityProvider<? extends TokenIdentity> lastUsedProvider;
/**
* @see #builder()
*/
private SdkTokenProviderChain(BuilderImpl builder) {
Validate.notEmpty(builder.tokenProviders, "No token providers were specified.");
this.reuseLastProviderEnabled = builder.reuseLastProviderEnabled;
this.sdkTokenProviders = Collections.unmodifiableList(builder.tokenProviders);
}
/**
* Get a new builder for creating a {@link SdkTokenProviderChain}.
*/
public static Builder builder() {
return new BuilderImpl();
}
/**
* Create a token provider chain with default configuration that checks the given token providers.
* @param sdkTokenProviders The token providers that should be checked for token, in the order they should
* be checked.
* @return A token provider chain that checks the provided token providers in order.
*/
public static SdkTokenProviderChain of(SdkTokenProvider... sdkTokenProviders) {
return builder().tokenProviders(sdkTokenProviders).build();
}
/**
* Create a token provider chain with default configuration that checks the given token providers.
* @param sdkTokenProviders The token providers that should be checked for token, in the order they should
* be checked.
* @return A token provider chain that checks the provided token providers in order.
*/
public static SdkTokenProviderChain of(IdentityProvider<? extends TokenIdentity>... sdkTokenProviders) {
return builder().tokenProviders(sdkTokenProviders).build();
}
@Override
public SdkToken resolveToken() {
if (reuseLastProviderEnabled && lastUsedProvider != null) {
TokenIdentity tokenIdentity = CompletableFutureUtils.joinLikeSync(lastUsedProvider.resolveIdentity());
return TokenUtils.toSdkToken(tokenIdentity);
}
List<String> exceptionMessages = null;
for (IdentityProvider<? extends TokenIdentity> provider : sdkTokenProviders) {
try {
TokenIdentity token = CompletableFutureUtils.joinLikeSync(provider.resolveIdentity());
log.debug(() -> "Loading token from " + provider);
lastUsedProvider = provider;
return TokenUtils.toSdkToken(token);
} catch (RuntimeException e) {
// Ignore any exceptions and move onto the next provider
String message = provider + ": " + e.getMessage();
log.debug(() -> "Unable to load token from " + message , e);
if (exceptionMessages == null) {
exceptionMessages = new ArrayList<>();
}
exceptionMessages.add(message);
}
}
throw SdkClientException.builder()
.message("Unable to load token from any of the providers in the chain " +
this + " : " + exceptionMessages)
.build();
}
@Override
public void close() {
sdkTokenProviders.forEach(c -> IoUtils.closeIfCloseable(c, null));
}
@Override
public String toString() {
return ToString.builder("SdkTokenProviderChain")
.add("tokenProviders", sdkTokenProviders)
.build();
}
/**
* A builder for a {@link SdkTokenProviderChain} that allows controlling its behavior.
*/
public interface Builder {
/**
* Controls whether the chain should reuse the last successful token provider in the chain. Reusing the last
* successful token provider will typically return token faster than searching through the chain.
*
* <p>
* By default, this is enabled
*/
Builder reuseLastProviderEnabled(Boolean reuseLastProviderEnabled);
/**
* Configure the token providers that should be checked for token, in the order they should be checked.
*/
Builder tokenProviders(Collection<? extends SdkTokenProvider> tokenProviders);
/**
* Configure the token providers that should be checked for token, in the order they should be checked.
*/
Builder tokenIdentityProviders(Collection<? extends IdentityProvider<? extends TokenIdentity>> tokenProviders);
/**
* Configure the token providers that should be checked for token, in the order they should be checked.
*/
default Builder tokenProviders(SdkTokenProvider... tokenProviders) {
return tokenProviders((IdentityProvider<? extends TokenIdentity>[]) tokenProviders);
}
/**
* Configure the token providers that should be checked for token, in the order they should be checked.
*/
default Builder tokenProviders(IdentityProvider<? extends TokenIdentity>... tokenProviders) {
throw new UnsupportedOperationException();
}
/**
* Add a token provider to the chain, after the token providers that have already been configured.
*/
default Builder addTokenProvider(SdkTokenProvider tokenProvider) {
return addTokenProvider((IdentityProvider<? extends TokenIdentity>) tokenProvider);
}
/**
* Add a token provider to the chain, after the token providers that have already been configured.
*/
default Builder addTokenProvider(IdentityProvider<? extends TokenIdentity> tokenProvider) {
throw new UnsupportedOperationException();
}
SdkTokenProviderChain build();
}
private static final class BuilderImpl implements Builder {
private Boolean reuseLastProviderEnabled = true;
private List<IdentityProvider<? extends TokenIdentity>> tokenProviders = new ArrayList<>();
private BuilderImpl() {
}
@Override
public Builder reuseLastProviderEnabled(Boolean reuseLastProviderEnabled) {
this.reuseLastProviderEnabled = reuseLastProviderEnabled;
return this;
}
public void setReuseLastProviderEnabled(Boolean reuseLastProviderEnabled) {
reuseLastProviderEnabled(reuseLastProviderEnabled);
}
@Override
public Builder tokenProviders(Collection<? extends SdkTokenProvider> tokenProviders) {
this.tokenProviders = new ArrayList<>(tokenProviders);
return this;
}
public void setTokenProviders(Collection<? extends SdkTokenProvider> tokenProviders) {
tokenProviders(tokenProviders);
}
@Override
public Builder tokenIdentityProviders(Collection<? extends IdentityProvider<? extends TokenIdentity>> tokenProviders) {
this.tokenProviders = new ArrayList<>(tokenProviders);
return this;
}
public void setTokenIdentityProviders(Collection<? extends IdentityProvider<? extends TokenIdentity>> tokenProviders) {
tokenIdentityProviders(tokenProviders);
}
public Builder tokenProviders(IdentityProvider<? extends TokenIdentity>... tokenProvider) {
return tokenIdentityProviders(Arrays.asList(tokenProvider));
}
@Override
public Builder addTokenProvider(IdentityProvider<? extends TokenIdentity> tokenProvider) {
this.tokenProviders.add(tokenProvider);
return this;
}
@Override
public SdkTokenProviderChain build() {
return new SdkTokenProviderChain(this);
}
}
}
| 1,706 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/token | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/token/credentials/SdkToken.java | /*
* 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.auth.token.credentials;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.identity.spi.TokenIdentity;
/**
* Provides token which is used to securely authorize requests to services that use token based auth, e.g., OAuth.
*
* <p>For more details on OAuth tokens, see:
* <a href="https://oauth.net/2/access-tokens">
* https://oauth.net/2/access-tokens</a></p>
*
* @see SdkTokenProvider
*/
@SdkPublicApi
public interface SdkToken extends TokenIdentity {
}
| 1,707 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/token/credentials | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/token/credentials/aws/DefaultAwsTokenProvider.java | /*
* 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.auth.token.credentials.aws;
import java.util.function.Supplier;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.auth.token.credentials.ProfileTokenProvider;
import software.amazon.awssdk.auth.token.credentials.SdkToken;
import software.amazon.awssdk.auth.token.credentials.SdkTokenProvider;
import software.amazon.awssdk.auth.token.credentials.SdkTokenProviderChain;
import software.amazon.awssdk.auth.token.internal.LazyTokenProvider;
import software.amazon.awssdk.profiles.ProfileFile;
import software.amazon.awssdk.utils.SdkAutoCloseable;
import software.amazon.awssdk.utils.ToString;
/**
* A token provider chain that looks for providers in this order:
* <ol>
* <li>A profile based provider that can initialize token providers based on profile configurations</li>
* </ol>
*
* @see ProfileTokenProvider
*/
@SdkPublicApi
public final class DefaultAwsTokenProvider implements SdkTokenProvider, SdkAutoCloseable {
private static final DefaultAwsTokenProvider DEFAULT_TOKEN_PROVIDER = new DefaultAwsTokenProvider(builder());
private final LazyTokenProvider providerChain;
private DefaultAwsTokenProvider(Builder builder) {
this.providerChain = createChain(builder);
}
public static DefaultAwsTokenProvider create() {
return DEFAULT_TOKEN_PROVIDER;
}
/**
* Create the default token provider chain using the configuration in the provided builder.
*/
private static LazyTokenProvider createChain(Builder builder) {
return LazyTokenProvider.create(
() -> SdkTokenProviderChain.of(ProfileTokenProvider.builder()
.profileFile(builder.profileFile)
.profileName(builder.profileName)
.build()));
}
/**
* Get a builder for defining a {@link DefaultAwsTokenProvider} with custom configuration.
*/
public static Builder builder() {
return new Builder();
}
@Override
public SdkToken resolveToken() {
return providerChain.resolveToken();
}
@Override
public void close() {
providerChain.close();
}
@Override
public String toString() {
return ToString.builder("DefaultAwsTokenProvider")
.add("providerChain", providerChain)
.build();
}
/**
* Configuration that defines the {@link DefaultAwsTokenProvider}'s behavior.
*/
public static final class Builder {
private Supplier<ProfileFile> profileFile;
private String profileName;
/**
* Created with {@link #builder()}.
*/
private Builder() {
}
public Builder profileFile(Supplier<ProfileFile> profileFile) {
this.profileFile = profileFile;
return this;
}
public Builder profileName(String profileName) {
this.profileName = profileName;
return this;
}
/**
* Create a {@link DefaultAwsTokenProvider} using the configuration defined in this builder.
*/
public DefaultAwsTokenProvider build() {
return new DefaultAwsTokenProvider(this);
}
}
}
| 1,708 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer/AwsSignerExecutionAttribute.java | /*
* 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.auth.signer;
import static software.amazon.awssdk.utils.CompletableFutureUtils.joinLikeSync;
import java.time.Clock;
import java.time.Instant;
import java.util.concurrent.CompletableFuture;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.auth.credentials.AwsCredentials;
import software.amazon.awssdk.auth.credentials.CredentialUtils;
import software.amazon.awssdk.auth.signer.params.Aws4SignerParams;
import software.amazon.awssdk.core.SelectedAuthScheme;
import software.amazon.awssdk.core.interceptor.ExecutionAttribute;
import software.amazon.awssdk.core.interceptor.ExecutionInterceptor;
import software.amazon.awssdk.core.interceptor.SdkExecutionAttribute;
import software.amazon.awssdk.core.interceptor.SdkInternalExecutionAttribute;
import software.amazon.awssdk.core.signer.Signer;
import software.amazon.awssdk.http.auth.aws.scheme.AwsV4AuthScheme;
import software.amazon.awssdk.http.auth.aws.signer.AwsV4FamilyHttpSigner;
import software.amazon.awssdk.http.auth.aws.signer.AwsV4HttpSigner;
import software.amazon.awssdk.http.auth.aws.signer.AwsV4aHttpSigner;
import software.amazon.awssdk.http.auth.aws.signer.RegionSet;
import software.amazon.awssdk.http.auth.spi.scheme.AuthSchemeOption;
import software.amazon.awssdk.http.auth.spi.signer.AsyncSignRequest;
import software.amazon.awssdk.http.auth.spi.signer.AsyncSignedRequest;
import software.amazon.awssdk.http.auth.spi.signer.HttpSigner;
import software.amazon.awssdk.http.auth.spi.signer.SignRequest;
import software.amazon.awssdk.http.auth.spi.signer.SignedRequest;
import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity;
import software.amazon.awssdk.identity.spi.Identity;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.regions.RegionScope;
import software.amazon.awssdk.utils.CompletableFutureUtils;
/**
* AWS-specific signing attributes attached to the execution. This information is available to {@link ExecutionInterceptor}s and
* {@link Signer}s.
*
* @deprecated Signer execution attributes have been deprecated in favor of signer properties, set on the auth scheme's signer
* option.
*/
@Deprecated
@SdkProtectedApi
public final class AwsSignerExecutionAttribute extends SdkExecutionAttribute {
/**
* The key under which the request credentials are set.
*
* @deprecated This is a protected class that is internal to the SDK, so you shouldn't be using it. If you are using it
* from execution interceptors, you should instead be overriding the credential provider via the {@code SdkRequest}'s
* {@code overrideConfiguration.credentialsProvider}. If you're using it to call the SDK's signers, you should migrate to a
* subtype of {@code HttpSigner}.
*/
@Deprecated
public static final ExecutionAttribute<AwsCredentials> AWS_CREDENTIALS =
ExecutionAttribute.derivedBuilder("AwsCredentials",
AwsCredentials.class,
SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME)
.readMapping(AwsSignerExecutionAttribute::awsCredentialsReadMapping)
.writeMapping(AwsSignerExecutionAttribute::awsCredentialsWriteMapping)
.build();
/**
* The AWS {@link Region} that is used for signing a request. This is not always same as the region configured on the client
* for global services like IAM.
*
* @deprecated This is a protected class that is internal to the SDK, so you shouldn't be using it. If you are using it
* from execution interceptors, you should instead be overriding the signing region via the {@code AuthSchemeProvider} that
* is configured on the SDK client builder. If you're using it to call the SDK's signers, you should migrate to a
* subtype of {@code HttpSigner}.
*/
@Deprecated
public static final ExecutionAttribute<Region> SIGNING_REGION =
ExecutionAttribute.derivedBuilder("SigningRegion",
Region.class,
SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME)
.readMapping(AwsSignerExecutionAttribute::signingRegionReadMapping)
.writeMapping(AwsSignerExecutionAttribute::signingRegionWriteMapping)
.build();
/**
* The AWS {@link Region} that is used for signing a request. This is not always same as the region configured on the client
* for global services like IAM.
*
* @deprecated This is a protected class that is internal to the SDK, so you shouldn't be using it. If you are using it
* from execution interceptors, you should instead be overriding the signing region scope via the {@code AuthSchemeProvider}
* that is configured on the SDK client builder. If you're using it to call the SDK's signers, you should migrate to a
* subtype of {@code HttpSigner}.
*/
@Deprecated
public static final ExecutionAttribute<RegionScope> SIGNING_REGION_SCOPE =
ExecutionAttribute.derivedBuilder("SigningRegionScope",
RegionScope.class,
SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME)
.readMapping(AwsSignerExecutionAttribute::signingRegionScopeReadMapping)
.writeMapping(AwsSignerExecutionAttribute::signingRegionScopeWriteMapping)
.build();
/**
* The signing name of the service to be using in SigV4 signing
*
* @deprecated This is a protected class that is internal to the SDK, so you shouldn't be using it. If you are using it
* from execution interceptors, you should instead be overriding the signing region name via the {@code AuthSchemeProvider}
* that is configured on the SDK client builder. If you're using it to call the SDK's signers, you should migrate to a
* subtype of {@code HttpSigner}.
*/
@Deprecated
public static final ExecutionAttribute<String> SERVICE_SIGNING_NAME =
ExecutionAttribute.derivedBuilder("ServiceSigningName",
String.class,
SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME)
.readMapping(AwsSignerExecutionAttribute::serviceSigningNameReadMapping)
.writeMapping(AwsSignerExecutionAttribute::serviceSigningNameWriteMapping)
.build();
/**
* The key to specify whether to use double url encoding during signing.
*
* @deprecated This is a protected class that is internal to the SDK, so you shouldn't be using it. If you are using it
* from execution interceptors, you should instead be overriding the double-url-encode setting via the {@code
* AuthSchemeProvider} that is configured on the SDK client builder. If you're using it to call the SDK's signers, you
* should migrate to a subtype of {@code HttpSigner}.
*/
@Deprecated
public static final ExecutionAttribute<Boolean> SIGNER_DOUBLE_URL_ENCODE =
ExecutionAttribute.derivedBuilder("DoubleUrlEncode",
Boolean.class,
SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME)
.readMapping(AwsSignerExecutionAttribute::signerDoubleUrlEncodeReadMapping)
.writeMapping(AwsSignerExecutionAttribute::signerDoubleUrlEncodeWriteMapping)
.build();
/**
* The key to specify whether to normalize the resource path during signing.
*
* @deprecated This is a protected class that is internal to the SDK, so you shouldn't be using it. If you are using it
* from execution interceptors, you should instead be overriding the normalize-path setting via the {@code
* AuthSchemeProvider} that is configured on the SDK client builder. If you're using it to call the SDK's signers, you
* should migrate to a subtype of {@code HttpSigner}.
*/
@Deprecated
public static final ExecutionAttribute<Boolean> SIGNER_NORMALIZE_PATH =
ExecutionAttribute.derivedBuilder("NormalizePath",
Boolean.class,
SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME)
.readMapping(AwsSignerExecutionAttribute::signerNormalizePathReadMapping)
.writeMapping(AwsSignerExecutionAttribute::signerNormalizePathWriteMapping)
.build();
/**
* An override clock to use during signing.
* @see Aws4SignerParams.Builder#signingClockOverride(Clock)
*
* @deprecated This is a protected class that is internal to the SDK, so you shouldn't be using it. If you are using it
* from execution interceptors, you should instead be overriding the clock setting via the {@code
* AuthSchemeProvider} that is configured on the SDK client builder. If you're using it to call the SDK's signers, you
* should migrate to a subtype of {@code HttpSigner}.
*/
@Deprecated
public static final ExecutionAttribute<Clock> SIGNING_CLOCK =
ExecutionAttribute.derivedBuilder("Clock",
Clock.class,
SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME)
.readMapping(AwsSignerExecutionAttribute::signingClockReadMapping)
.writeMapping(AwsSignerExecutionAttribute::signingClockWriteMapping)
.build();
/**
* The key to specify the expiration time when pre-signing aws requests.
*
* @deprecated This is a protected class that is internal to the SDK, so you shouldn't be using it. If you are using it
* from execution interceptors, you should instead be overriding the expiration via the {@code AuthSchemeProvider} that is
* configured on the SDK client builder. If you're using it to call the SDK's signers, you should migrate to a subtype of
* {@code HttpSigner}.
*/
@Deprecated
public static final ExecutionAttribute<Instant> PRESIGNER_EXPIRATION = new ExecutionAttribute("PresignerExpiration");
private AwsSignerExecutionAttribute() {
}
private static AwsCredentials awsCredentialsReadMapping(SelectedAuthScheme<?> authScheme) {
if (authScheme == null) {
return null;
}
Identity identity = joinLikeSync(authScheme.identity());
if (!(identity instanceof AwsCredentialsIdentity)) {
return null;
}
return CredentialUtils.toCredentials((AwsCredentialsIdentity) identity);
}
private static <T extends Identity> SelectedAuthScheme<?> awsCredentialsWriteMapping(SelectedAuthScheme<T> authScheme,
AwsCredentials awsCredentials) {
if (authScheme == null) {
// This is an unusual use-case.
// Let's assume they're setting the credentials so that they can call the signer directly. If that's true, then it
// doesn't really matter what we store other than the credentials.
return new SelectedAuthScheme<>(CompletableFuture.completedFuture(awsCredentials),
AwsV4HttpSigner.create(),
AuthSchemeOption.builder()
.schemeId(AwsV4AuthScheme.SCHEME_ID)
.build());
}
return new SelectedAuthScheme<>(CompletableFuture.completedFuture((T) awsCredentials),
authScheme.signer(),
authScheme.authSchemeOption());
}
private static Region signingRegionReadMapping(SelectedAuthScheme<?> authScheme) {
if (authScheme == null) {
return null;
}
String regionName = authScheme.authSchemeOption().signerProperty(AwsV4HttpSigner.REGION_NAME);
if (regionName == null) {
return null;
}
return Region.of(regionName);
}
private static <T extends Identity> SelectedAuthScheme<?> signingRegionWriteMapping(SelectedAuthScheme<T> authScheme,
Region region) {
String regionString = region == null ? null : region.id();
if (authScheme == null) {
// This is an unusual use-case.
// Let's assume they're setting the region so that they can call the signer directly. If that's true, then it
// doesn't really matter what we store other than the region.
return new SelectedAuthScheme<>(CompletableFuture.completedFuture(new UnsetIdentity()),
new UnsetHttpSigner(),
AuthSchemeOption.builder()
.schemeId("unset")
.putSignerProperty(AwsV4HttpSigner.REGION_NAME,
regionString)
.build());
}
return new SelectedAuthScheme<>(authScheme.identity(),
authScheme.signer(),
authScheme.authSchemeOption().copy(o -> o.putSignerProperty(AwsV4HttpSigner.REGION_NAME,
regionString)));
}
private static RegionScope signingRegionScopeReadMapping(SelectedAuthScheme<?> authScheme) {
if (authScheme == null) {
return null;
}
RegionSet regionSet = authScheme.authSchemeOption().signerProperty(AwsV4aHttpSigner.REGION_SET);
if (regionSet == null || regionSet.asString().isEmpty()) {
return null;
}
return RegionScope.create(regionSet.asString());
}
private static <T extends Identity> SelectedAuthScheme<?> signingRegionScopeWriteMapping(SelectedAuthScheme<T> authScheme,
RegionScope regionScope) {
RegionSet regionSet = regionScope != null ? RegionSet.create(regionScope.id()) : null;
if (authScheme == null) {
// This is an unusual use-case.
// Let's assume they're setting the region scope so that they can call the signer directly. If that's true, then it
// doesn't really matter what we store other than the region scope.
return new SelectedAuthScheme<>(CompletableFuture.completedFuture(new UnsetIdentity()),
new UnsetHttpSigner(),
AuthSchemeOption.builder()
.schemeId("unset")
.putSignerProperty(AwsV4aHttpSigner.REGION_SET, regionSet)
.build());
}
return new SelectedAuthScheme<>(authScheme.identity(),
authScheme.signer(),
authScheme.authSchemeOption().copy(o -> o.putSignerProperty(AwsV4aHttpSigner.REGION_SET,
regionSet)));
}
private static String serviceSigningNameReadMapping(SelectedAuthScheme<?> authScheme) {
if (authScheme == null) {
return null;
}
return authScheme.authSchemeOption().signerProperty(AwsV4FamilyHttpSigner.SERVICE_SIGNING_NAME);
}
private static <T extends Identity> SelectedAuthScheme<?> serviceSigningNameWriteMapping(SelectedAuthScheme<T> authScheme,
String signingName) {
if (authScheme == null) {
// This is an unusual use-case.
// Let's assume they're setting the signing name so that they can call the signer directly. If that's true, then it
// doesn't really matter what we store other than the signing name.
return new SelectedAuthScheme<>(CompletableFuture.completedFuture(new UnsetIdentity()),
new UnsetHttpSigner(),
AuthSchemeOption.builder()
.schemeId("unset")
.putSignerProperty(AwsV4FamilyHttpSigner.SERVICE_SIGNING_NAME,
signingName)
.build());
}
return new SelectedAuthScheme<>(authScheme.identity(),
authScheme.signer(),
authScheme.authSchemeOption()
.copy(o -> o.putSignerProperty(AwsV4FamilyHttpSigner.SERVICE_SIGNING_NAME,
signingName)));
}
private static Boolean signerDoubleUrlEncodeReadMapping(SelectedAuthScheme<?> authScheme) {
if (authScheme == null) {
return null;
}
AuthSchemeOption authOption = authScheme.authSchemeOption();
return authOption.signerProperty(AwsV4FamilyHttpSigner.DOUBLE_URL_ENCODE);
}
private static <T extends Identity> SelectedAuthScheme<?> signerDoubleUrlEncodeWriteMapping(SelectedAuthScheme<T> authScheme,
Boolean doubleUrlEncode) {
if (authScheme == null) {
// This is an unusual use-case.
// Let's assume they're setting double-url-encode so that they can call the signer directly. If that's true, then it
// doesn't really matter what we store other than double-url-encode.
return new SelectedAuthScheme<>(CompletableFuture.completedFuture(new UnsetIdentity()),
new UnsetHttpSigner(),
AuthSchemeOption.builder()
.schemeId("unset")
.putSignerProperty(AwsV4FamilyHttpSigner.DOUBLE_URL_ENCODE,
doubleUrlEncode)
.build());
}
return new SelectedAuthScheme<>(authScheme.identity(),
authScheme.signer(),
authScheme.authSchemeOption()
.copy(o -> o.putSignerProperty(AwsV4FamilyHttpSigner.DOUBLE_URL_ENCODE,
doubleUrlEncode)));
}
private static Boolean signerNormalizePathReadMapping(SelectedAuthScheme<?> authScheme) {
if (authScheme == null) {
return null;
}
AuthSchemeOption authOption = authScheme.authSchemeOption();
return authOption.signerProperty(AwsV4FamilyHttpSigner.NORMALIZE_PATH);
}
private static <T extends Identity> SelectedAuthScheme<?> signerNormalizePathWriteMapping(SelectedAuthScheme<T> authScheme,
Boolean normalizePath) {
if (authScheme == null) {
// This is an unusual use-case.
// Let's assume they're setting normalize-path so that they can call the signer directly. If that's true, then it
// doesn't really matter what we store other than normalize-path.
return new SelectedAuthScheme<>(CompletableFuture.completedFuture(new UnsetIdentity()),
new UnsetHttpSigner(),
AuthSchemeOption.builder()
.schemeId("unset")
.putSignerProperty(AwsV4FamilyHttpSigner.NORMALIZE_PATH,
normalizePath)
.build());
}
return new SelectedAuthScheme<>(authScheme.identity(),
authScheme.signer(),
authScheme.authSchemeOption()
.copy(o -> o.putSignerProperty(AwsV4FamilyHttpSigner.NORMALIZE_PATH,
normalizePath)));
}
private static Clock signingClockReadMapping(SelectedAuthScheme<?> authScheme) {
if (authScheme == null) {
return null;
}
return authScheme.authSchemeOption().signerProperty(HttpSigner.SIGNING_CLOCK);
}
private static <T extends Identity> SelectedAuthScheme<?> signingClockWriteMapping(SelectedAuthScheme<T> authScheme,
Clock clock) {
if (authScheme == null) {
// This is an unusual use-case.
// Let's assume they're setting signing clock so that they can call the signer directly. If that's true, then it
// doesn't really matter what we store other than the signing clock.
return new SelectedAuthScheme<>(CompletableFuture.completedFuture(new UnsetIdentity()),
new UnsetHttpSigner(),
AuthSchemeOption.builder()
.schemeId("unset")
.putSignerProperty(HttpSigner.SIGNING_CLOCK, clock)
.build());
}
return new SelectedAuthScheme<>(authScheme.identity(),
authScheme.signer(),
authScheme.authSchemeOption()
.copy(o -> o.putSignerProperty(HttpSigner.SIGNING_CLOCK, clock)));
}
private static class UnsetIdentity implements Identity {
}
private static class UnsetHttpSigner implements HttpSigner<UnsetIdentity> {
@Override
public SignedRequest sign(SignRequest<? extends UnsetIdentity> request) {
throw new IllegalStateException("A signer was not configured.");
}
@Override
public CompletableFuture<AsyncSignedRequest> signAsync(AsyncSignRequest<? extends UnsetIdentity> request) {
return CompletableFutureUtils.failedFuture(new IllegalStateException("A signer was not configured."));
}
}
}
| 1,709 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer/S3SignerExecutionAttribute.java | /*
* 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.auth.signer;
import java.util.concurrent.CompletableFuture;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.core.SelectedAuthScheme;
import software.amazon.awssdk.core.interceptor.ExecutionAttribute;
import software.amazon.awssdk.core.interceptor.SdkExecutionAttribute;
import software.amazon.awssdk.core.interceptor.SdkInternalExecutionAttribute;
import software.amazon.awssdk.http.auth.aws.signer.AwsV4FamilyHttpSigner;
import software.amazon.awssdk.http.auth.spi.scheme.AuthSchemeOption;
import software.amazon.awssdk.http.auth.spi.signer.AsyncSignRequest;
import software.amazon.awssdk.http.auth.spi.signer.AsyncSignedRequest;
import software.amazon.awssdk.http.auth.spi.signer.HttpSigner;
import software.amazon.awssdk.http.auth.spi.signer.SignRequest;
import software.amazon.awssdk.http.auth.spi.signer.SignedRequest;
import software.amazon.awssdk.identity.spi.Identity;
import software.amazon.awssdk.utils.CompletableFutureUtils;
/**
* S3-specific signing attributes attached to the execution.
*
* @deprecated Signer execution attributes have been deprecated in favor of signer properties, set on the auth scheme's signer
* option.
*/
@SdkProtectedApi
@Deprecated
public final class S3SignerExecutionAttribute extends SdkExecutionAttribute {
/**
* The key to specify whether to enable chunked encoding or not
*
* @deprecated This is a protected class that is internal to the SDK, so you shouldn't be using it. If you are using it
* from execution interceptors, you should instead be overriding the chunk encoding setting via the {@code AuthSchemeProvider}
* that is configured on the SDK client builder. If you're using it to call the SDK's signers, you should migrate to a
* subtype of {@code HttpSigner}.
*/
@Deprecated
public static final ExecutionAttribute<Boolean> ENABLE_CHUNKED_ENCODING =
ExecutionAttribute.derivedBuilder("ChunkedEncoding",
Boolean.class,
SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME)
.readMapping(S3SignerExecutionAttribute::enableChunkedEncodingReadMapping)
.writeMapping(S3SignerExecutionAttribute::enableChunkedEncodingWriteMapping)
.build();
/**
* The key to specify whether to enable payload signing or not
*
* @deprecated This is a protected class that is internal to the SDK, so you shouldn't be using it. If you are using it
* from execution interceptors, you should instead be overriding the payload signing setting via the {@code
* AuthSchemeProvider} that is configured on the SDK client builder. If you're using it to call the SDK's signers, you
* should migrate to a subtype of {@code HttpSigner}.
*/
@Deprecated
public static final ExecutionAttribute<Boolean> ENABLE_PAYLOAD_SIGNING =
ExecutionAttribute.derivedBuilder("PayloadSigning",
Boolean.class,
SdkInternalExecutionAttribute.SELECTED_AUTH_SCHEME)
.readMapping(S3SignerExecutionAttribute::enablePayloadSigningReadMapping)
.writeMapping(S3SignerExecutionAttribute::enablePayloadSigningWriteMapping)
.build();
private S3SignerExecutionAttribute() {
}
private static Boolean enableChunkedEncodingReadMapping(SelectedAuthScheme<?> authScheme) {
if (authScheme == null) {
return null;
}
AuthSchemeOption authOption = authScheme.authSchemeOption();
return authOption.signerProperty(AwsV4FamilyHttpSigner.CHUNK_ENCODING_ENABLED);
}
private static <T extends Identity> SelectedAuthScheme<?> enableChunkedEncodingWriteMapping(SelectedAuthScheme<T> authScheme,
Boolean enableChunkedEncoding) {
if (authScheme == null) {
// This is an unusual use-case.
// Let's assume they're setting chunked-encoding so that they can call the signer directly. If that's true, then it
// doesn't really matter what we store other than chunked-encoding.
return new SelectedAuthScheme<>(CompletableFuture.completedFuture(new UnsetIdentity()),
new UnsetHttpSigner(),
AuthSchemeOption.builder()
.schemeId("unset")
.putSignerProperty(AwsV4FamilyHttpSigner.CHUNK_ENCODING_ENABLED,
enableChunkedEncoding)
.build());
}
return new SelectedAuthScheme<>(authScheme.identity(),
authScheme.signer(),
authScheme.authSchemeOption()
.copy(o -> o.putSignerProperty(AwsV4FamilyHttpSigner.CHUNK_ENCODING_ENABLED,
enableChunkedEncoding)));
}
private static Boolean enablePayloadSigningReadMapping(SelectedAuthScheme<?> authScheme) {
if (authScheme == null) {
return null;
}
return authScheme.authSchemeOption().signerProperty(AwsV4FamilyHttpSigner.PAYLOAD_SIGNING_ENABLED);
}
private static <T extends Identity> SelectedAuthScheme<?> enablePayloadSigningWriteMapping(SelectedAuthScheme<T> authScheme,
Boolean payloadSigningEnabled) {
if (authScheme == null) {
// This is an unusual use-case.
// Let's assume they're configuring payload signing so that they can call the signer directly. If that's true, then it
// doesn't really matter what we store other than the payload signing setting.
return new SelectedAuthScheme<>(CompletableFuture.completedFuture(new UnsetIdentity()),
new UnsetHttpSigner(),
AuthSchemeOption.builder()
.schemeId("unset")
.putSignerProperty(AwsV4FamilyHttpSigner.PAYLOAD_SIGNING_ENABLED,
payloadSigningEnabled)
.build());
}
return new SelectedAuthScheme<>(authScheme.identity(),
authScheme.signer(),
authScheme.authSchemeOption()
.copy(o -> o.putSignerProperty(AwsV4FamilyHttpSigner.PAYLOAD_SIGNING_ENABLED,
payloadSigningEnabled))
);
}
private static class UnsetIdentity implements Identity {
}
private static class UnsetHttpSigner implements HttpSigner<UnsetIdentity> {
@Override
public SignedRequest sign(SignRequest<? extends UnsetIdentity> request) {
throw new IllegalStateException("A signer was not configured.");
}
@Override
public CompletableFuture<AsyncSignedRequest> signAsync(AsyncSignRequest<? extends UnsetIdentity> request) {
return CompletableFutureUtils.failedFuture(new IllegalStateException("A signer was not configured."));
}
}
}
| 1,710 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer/SignerLoader.java | /*
* 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.auth.signer;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.core.internal.util.ClassLoaderHelper;
import software.amazon.awssdk.core.signer.Signer;
/**
* Utility class for instantiating signers only if they're available on the class path.
*/
@SdkProtectedApi
public final class SignerLoader {
private static final Map<String, Signer> SIGNERS = new ConcurrentHashMap<>();
private SignerLoader() {
}
public static Signer getSigV4aSigner() {
return get("software.amazon.awssdk.authcrt.signer.AwsCrtV4aSigner");
}
public static Signer getS3SigV4aSigner() {
return get("software.amazon.awssdk.authcrt.signer.AwsCrtS3V4aSigner");
}
private static Signer get(String fqcn) {
return SIGNERS.computeIfAbsent(fqcn, SignerLoader::initializeV4aSigner);
}
private static Signer initializeV4aSigner(String fqcn) {
try {
Class<?> signerClass = ClassLoaderHelper.loadClass(fqcn, false, (Class) null);
Method m = signerClass.getDeclaredMethod("create");
Object o = m.invoke(null);
return (Signer) o;
} catch (ClassNotFoundException e) {
throw new IllegalStateException("Cannot find the " + fqcn + " class."
+ " To invoke a request that requires a SigV4a signer, such as region independent " +
"signing, the 'auth-crt' core module must be on the class path. ", e);
} catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
throw new IllegalStateException("Failed to create " + fqcn, e);
}
}
}
| 1,711 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer/AwsS3V4Signer.java | /*
* 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.auth.signer;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.auth.signer.internal.AbstractAwsS3V4Signer;
/**
* AWS4 signer implementation for AWS S3
*/
@SdkPublicApi
public final class AwsS3V4Signer extends AbstractAwsS3V4Signer {
private AwsS3V4Signer() {
}
public static AwsS3V4Signer create() {
return new AwsS3V4Signer();
}
}
| 1,712 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer/EventStreamAws4Signer.java | /*
* 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.auth.signer;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.auth.signer.internal.BaseEventStreamAsyncAws4Signer;
@SdkProtectedApi
public final class EventStreamAws4Signer extends BaseEventStreamAsyncAws4Signer {
private EventStreamAws4Signer() {
}
public static EventStreamAws4Signer create() {
return new EventStreamAws4Signer();
}
}
| 1,713 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer/Aws4UnsignedPayloadSigner.java | /*
* 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.auth.signer;
import static software.amazon.awssdk.auth.signer.internal.SignerConstant.X_AMZ_CONTENT_SHA256;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.auth.signer.internal.BaseAws4Signer;
import software.amazon.awssdk.auth.signer.params.Aws4SignerParams;
import software.amazon.awssdk.core.checksums.SdkChecksum;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.http.SdkHttpFullRequest;
/**
* Exactly the same as {@link Aws4Signer} except if the request is being sent
* over HTTPS, then it returns the string <code>UNSIGNED-PAYLOAD</code> as the
* content SHA-256 so services that support it can avoid needing to calculate
* the value when authorizing the request.
* <p>
* Payloads are still signed for requests over HTTP to preserve the request
* integrity over a non-secure transport.
*/
@SdkPublicApi
public final class Aws4UnsignedPayloadSigner extends BaseAws4Signer {
public static final String UNSIGNED_PAYLOAD = "UNSIGNED-PAYLOAD";
private Aws4UnsignedPayloadSigner() {
}
public static Aws4UnsignedPayloadSigner create() {
return new Aws4UnsignedPayloadSigner();
}
@Override
public SdkHttpFullRequest sign(SdkHttpFullRequest request, ExecutionAttributes executionAttributes) {
request = addContentSha256Header(request);
return super.sign(request, executionAttributes);
}
@Override
public SdkHttpFullRequest sign(SdkHttpFullRequest request, Aws4SignerParams signingParams) {
request = addContentSha256Header(request);
return super.sign(request, signingParams);
}
@Override
protected String calculateContentHash(SdkHttpFullRequest.Builder mutableRequest, Aws4SignerParams signerParams,
SdkChecksum contentFlexibleChecksum) {
if ("https".equals(mutableRequest.protocol())) {
return UNSIGNED_PAYLOAD;
}
return super.calculateContentHash(mutableRequest, signerParams, contentFlexibleChecksum);
}
private SdkHttpFullRequest addContentSha256Header(SdkHttpFullRequest request) {
return request.toBuilder().putHeader(X_AMZ_CONTENT_SHA256, "required").build();
}
}
| 1,714 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer/AsyncAws4Signer.java | /*
* 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.auth.signer;
import java.util.concurrent.CompletableFuture;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.auth.credentials.CredentialUtils;
import software.amazon.awssdk.auth.signer.internal.Aws4SignerRequestParams;
import software.amazon.awssdk.auth.signer.internal.BaseAws4Signer;
import software.amazon.awssdk.auth.signer.internal.ContentChecksum;
import software.amazon.awssdk.auth.signer.internal.DigestComputingSubscriber;
import software.amazon.awssdk.auth.signer.params.Aws4SignerParams;
import software.amazon.awssdk.core.async.AsyncRequestBody;
import software.amazon.awssdk.core.checksums.SdkChecksum;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.core.signer.AsyncSigner;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.utils.BinaryUtils;
import software.amazon.awssdk.utils.CompletableFutureUtils;
/**
* AWS Signature Version 4 signer that can include contents of an asynchronous request body into the signature
* calculation.
*/
@SdkPublicApi
public final class AsyncAws4Signer extends BaseAws4Signer implements AsyncSigner {
@Override
public CompletableFuture<SdkHttpFullRequest> sign(SdkHttpFullRequest request,
AsyncRequestBody requestBody,
ExecutionAttributes executionAttributes) {
Aws4SignerParams signingParams = extractSignerParams(Aws4SignerParams.builder(), executionAttributes).build();
return signWithBody(request, requestBody, signingParams);
}
public CompletableFuture<SdkHttpFullRequest> signWithBody(SdkHttpFullRequest request,
AsyncRequestBody requestBody,
Aws4SignerParams signingParams) {
// anonymous credentials, don't sign
if (CredentialUtils.isAnonymous(signingParams.awsCredentials())) {
return CompletableFuture.completedFuture(request);
}
SdkChecksum sdkChecksum = createSdkChecksumFromParams(signingParams);
DigestComputingSubscriber bodyDigester = sdkChecksum != null
? DigestComputingSubscriber.forSha256(sdkChecksum)
: DigestComputingSubscriber.forSha256();
requestBody.subscribe(bodyDigester);
CompletableFuture<byte[]> digestBytes = bodyDigester.digestBytes();
CompletableFuture<SdkHttpFullRequest> signedReqFuture = digestBytes.thenApply(bodyHash -> {
String digestHex = BinaryUtils.toHex(bodyHash);
Aws4SignerRequestParams requestParams = new Aws4SignerRequestParams(signingParams);
SdkHttpFullRequest.Builder builder = doSign(request, requestParams, signingParams,
new ContentChecksum(digestHex, sdkChecksum));
return builder.build();
});
return CompletableFutureUtils.forwardExceptionTo(signedReqFuture, digestBytes);
}
private SdkChecksum createSdkChecksumFromParams(Aws4SignerParams signingParams) {
if (signingParams.checksumParams() != null) {
return SdkChecksum.forAlgorithm(signingParams.checksumParams().algorithm());
}
return null;
}
public static AsyncAws4Signer create() {
return new AsyncAws4Signer();
}
}
| 1,715 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer/Aws4Signer.java | /*
* 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.auth.signer;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.auth.signer.internal.BaseAws4Signer;
/**
* Signer implementation that signs requests with the AWS4 signing protocol.
*/
@SdkPublicApi
public final class Aws4Signer extends BaseAws4Signer {
private Aws4Signer() {
}
public static Aws4Signer create() {
return new Aws4Signer();
}
}
| 1,716 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer/internal/SigningAlgorithm.java | /*
* 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.auth.signer.internal;
import java.security.NoSuchAlgorithmException;
import javax.crypto.Mac;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.core.exception.SdkClientException;
@SdkInternalApi
public enum SigningAlgorithm {
HmacSHA256;
private final ThreadLocal<Mac> macReference;
SigningAlgorithm() {
String algorithmName = this.toString();
macReference = new MacThreadLocal(algorithmName);
}
/**
* Returns the thread local reference for the crypto algorithm
*/
public Mac getMac() {
return macReference.get();
}
private static class MacThreadLocal extends ThreadLocal<Mac> {
private final String algorithmName;
MacThreadLocal(String algorithmName) {
this.algorithmName = algorithmName;
}
@Override
protected Mac initialValue() {
try {
return Mac.getInstance(algorithmName);
} catch (NoSuchAlgorithmException e) {
throw SdkClientException.builder()
.message("Unable to fetch Mac instance for Algorithm "
+ algorithmName + e.getMessage())
.cause(e)
.build();
}
}
}
}
| 1,717 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer/internal/BoundedLinkedHashMap.java | /*
* 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.auth.signer.internal;
import java.util.LinkedHashMap;
import java.util.Map;
import software.amazon.awssdk.annotations.SdkInternalApi;
/**
* A bounded linked hash map that would remove the eldest entry when the map
* size exceeds a configurable maximum.
*/
@SdkInternalApi
final class BoundedLinkedHashMap<K, V> extends LinkedHashMap<K, V> {
private static final long serialVersionUID = 1L;
private final int maxSize;
BoundedLinkedHashMap(int maxSize) {
this.maxSize = maxSize;
}
/**
* {@inheritDoc}
*
* Returns true if the size of this map exceeds the maximum.
*/
@Override
protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
return size() > maxSize;
}
/**
* Returns the maximum size of this map beyond which the eldest entry
* will get removed.
*/
int getMaxSize() {
return maxSize;
}
}
| 1,718 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer/internal/Aws4SignerRequestParams.java | /*
* 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.auth.signer.internal;
import java.time.Clock;
import java.time.Duration;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.auth.signer.params.Aws4SignerParams;
import software.amazon.awssdk.regions.Region;
/**
* Parameters that are used for computing a AWS 4 signature for a request.
*/
@SdkInternalApi
public final class Aws4SignerRequestParams {
private final Clock signingClock;
private final long requestSigningDateTimeMilli;
/**
* The scope of the signature.
*/
private final String scope;
/**
* The AWS region to be used for computing the signature.
*/
private final String regionName;
/**
* The name of the AWS service.
*/
private final String serviceSigningName;
/**
* UTC formatted version of the signing time stamp.
*/
private final String formattedRequestSigningDateTime;
/**
* UTC Formatted Signing date with time stamp stripped.
*/
private final String formattedRequestSigningDate;
/**
* Generates an instance of AWS4signerRequestParams that holds the
* parameters used for computing a AWS 4 signature for a request based on
* the given {@link Aws4SignerParams} for that request.
*/
public Aws4SignerRequestParams(Aws4SignerParams signerParams) {
this.signingClock = resolveSigningClock(signerParams);
this.requestSigningDateTimeMilli = this.signingClock.millis();
this.formattedRequestSigningDate = Aws4SignerUtils.formatDateStamp(requestSigningDateTimeMilli);
this.serviceSigningName = signerParams.signingName();
this.regionName = getRegion(signerParams.signingRegion());
this.scope = generateScope(formattedRequestSigningDate, this.serviceSigningName, regionName);
this.formattedRequestSigningDateTime = Aws4SignerUtils.formatTimestamp(requestSigningDateTimeMilli);
}
/**
* @return The clock to use for signing additional data i.e. events or chunks.
*/
public Clock getSigningClock() {
return signingClock;
}
/**
* Returns the scope of the request signing.
*/
public String getScope() {
return scope;
}
/**
* Returns the formatted date and time of the request signing date in UTC
* zone.
*/
public String getFormattedRequestSigningDateTime() {
return formattedRequestSigningDateTime;
}
/**
* Returns the request signing date time in millis for which the request
* signature needs to be computed.
*/
public long getRequestSigningDateTimeMilli() {
return requestSigningDateTimeMilli;
}
/**
* Returns the AWS region name to be used while computing the signature.
*/
public String getRegionName() {
return regionName;
}
/**
* Returns the AWS Service name to be used while computing the signature.
*/
public String getServiceSigningName() {
return serviceSigningName;
}
/**
* Returns the formatted date in UTC zone of the signing date for the
* request.
*/
public String getFormattedRequestSigningDate() {
return formattedRequestSigningDate;
}
/**
* Returns the signing algorithm used for computing the signature.
*/
public String getSigningAlgorithm() {
return SignerConstant.AWS4_SIGNING_ALGORITHM;
}
private Clock resolveSigningClock(Aws4SignerParams signerParams) {
if (signerParams.signingClockOverride().isPresent()) {
return signerParams.signingClockOverride().get();
}
Clock baseClock = Clock.systemUTC();
return signerParams.timeOffset()
.map(offset -> Clock.offset(baseClock, Duration.ofSeconds(-offset)))
.orElse(baseClock);
}
private String getRegion(Region region) {
return region != null ? region.id() : null;
}
/**
* Returns the scope to be used for the signing.
*/
private String generateScope(String dateStamp, String serviceName, String regionName) {
return dateStamp + "/" + regionName + "/" + serviceName + "/" + SignerConstant.AWS4_TERMINATOR;
}
}
| 1,719 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer/internal/AbstractAws4Signer.java | /*
* 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.auth.signer.internal;
import static software.amazon.awssdk.auth.signer.Aws4UnsignedPayloadSigner.UNSIGNED_PAYLOAD;
import static software.amazon.awssdk.core.interceptor.SdkExecutionAttribute.RESOLVED_CHECKSUM_SPECS;
import static software.amazon.awssdk.utils.StringUtils.lowerCase;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.SortedMap;
import java.util.TreeMap;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.auth.credentials.AwsCredentials;
import software.amazon.awssdk.auth.credentials.AwsSessionCredentials;
import software.amazon.awssdk.auth.signer.Aws4Signer;
import software.amazon.awssdk.auth.signer.AwsSignerExecutionAttribute;
import software.amazon.awssdk.auth.signer.params.Aws4PresignerParams;
import software.amazon.awssdk.auth.signer.params.Aws4SignerParams;
import software.amazon.awssdk.auth.signer.params.SignerChecksumParams;
import software.amazon.awssdk.core.checksums.ChecksumSpecs;
import software.amazon.awssdk.core.checksums.SdkChecksum;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.core.internal.util.HttpChecksumUtils;
import software.amazon.awssdk.core.signer.Presigner;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.http.SdkHttpRequest;
import software.amazon.awssdk.utils.BinaryUtils;
import software.amazon.awssdk.utils.Logger;
import software.amazon.awssdk.utils.Pair;
import software.amazon.awssdk.utils.StringUtils;
import software.amazon.awssdk.utils.http.SdkHttpUtils;
/**
* Abstract base class for the AWS SigV4 signer implementations.
* @param <T> Type of the signing params class that is used for signing the request
* @param <U> Type of the signing params class that is used for pre signing the request
*/
@SdkInternalApi
public abstract class AbstractAws4Signer<T extends Aws4SignerParams, U extends Aws4PresignerParams>
extends AbstractAwsSigner implements Presigner {
public static final String EMPTY_STRING_SHA256_HEX = BinaryUtils.toHex(hash(""));
private static final Logger LOG = Logger.loggerFor(Aws4Signer.class);
private static final int SIGNER_CACHE_MAX_SIZE = 300;
private static final FifoCache<SignerKey> SIGNER_CACHE =
new FifoCache<>(SIGNER_CACHE_MAX_SIZE);
private static final List<String> LIST_OF_HEADERS_TO_IGNORE_IN_LOWER_CASE =
Arrays.asList("connection", "x-amzn-trace-id", "user-agent", "expect");
protected SdkHttpFullRequest.Builder doSign(SdkHttpFullRequest request,
Aws4SignerRequestParams requestParams,
T signingParams) {
SdkHttpFullRequest.Builder mutableRequest = request.toBuilder();
SdkChecksum sdkChecksum = createSdkChecksumFromParams(signingParams, request);
String contentHash = calculateContentHash(mutableRequest, signingParams, sdkChecksum);
return doSign(mutableRequest.build(), requestParams, signingParams,
new ContentChecksum(contentHash, sdkChecksum));
}
protected SdkHttpFullRequest.Builder doSign(SdkHttpFullRequest request,
Aws4SignerRequestParams requestParams,
T signingParams,
ContentChecksum contentChecksum) {
SdkHttpFullRequest.Builder mutableRequest = request.toBuilder();
AwsCredentials sanitizedCredentials = sanitizeCredentials(signingParams.awsCredentials());
if (sanitizedCredentials instanceof AwsSessionCredentials) {
addSessionCredentials(mutableRequest, (AwsSessionCredentials) sanitizedCredentials);
}
addHostHeader(mutableRequest);
addDateHeader(mutableRequest, requestParams.getFormattedRequestSigningDateTime());
mutableRequest.firstMatchingHeader(SignerConstant.X_AMZ_CONTENT_SHA256)
.filter(h -> h.equals("required"))
.ifPresent(h -> mutableRequest.putHeader(
SignerConstant.X_AMZ_CONTENT_SHA256, contentChecksum.contentHash()));
putChecksumHeader(signingParams.checksumParams(), contentChecksum.contentFlexibleChecksum(),
mutableRequest, contentChecksum.contentHash());
CanonicalRequest canonicalRequest = createCanonicalRequest(request,
mutableRequest,
contentChecksum.contentHash(),
signingParams.doubleUrlEncode(),
signingParams.normalizePath());
String canonicalRequestString = canonicalRequest.string();
String stringToSign = createStringToSign(canonicalRequestString, requestParams);
byte[] signingKey = deriveSigningKey(sanitizedCredentials, requestParams);
byte[] signature = computeSignature(stringToSign, signingKey);
mutableRequest.putHeader(SignerConstant.AUTHORIZATION,
buildAuthorizationHeader(signature, sanitizedCredentials, requestParams, canonicalRequest));
processRequestPayload(mutableRequest, signature, signingKey, requestParams, signingParams,
contentChecksum.contentFlexibleChecksum());
return mutableRequest;
}
protected SdkHttpFullRequest.Builder doPresign(SdkHttpFullRequest request,
Aws4SignerRequestParams requestParams,
U signingParams) {
SdkHttpFullRequest.Builder mutableRequest = request.toBuilder();
long expirationInSeconds = getSignatureDurationInSeconds(requestParams, signingParams);
addHostHeader(mutableRequest);
AwsCredentials sanitizedCredentials = sanitizeCredentials(signingParams.awsCredentials());
if (sanitizedCredentials instanceof AwsSessionCredentials) {
// For SigV4 pre-signing URL, we need to add "X-Amz-Security-Token"
// as a query string parameter, before constructing the canonical
// request.
mutableRequest.putRawQueryParameter(SignerConstant.X_AMZ_SECURITY_TOKEN,
((AwsSessionCredentials) sanitizedCredentials).sessionToken());
}
// Add the important parameters for v4 signing
String contentSha256 = calculateContentHashPresign(mutableRequest, signingParams);
CanonicalRequest canonicalRequest = createCanonicalRequest(request,
mutableRequest,
contentSha256,
signingParams.doubleUrlEncode(),
signingParams.normalizePath());
addPreSignInformationToRequest(mutableRequest, canonicalRequest, sanitizedCredentials,
requestParams, expirationInSeconds);
String string = canonicalRequest.string();
String stringToSign = createStringToSign(string, requestParams);
byte[] signingKey = deriveSigningKey(sanitizedCredentials, requestParams);
byte[] signature = computeSignature(stringToSign, signingKey);
mutableRequest.putRawQueryParameter(SignerConstant.X_AMZ_SIGNATURE, BinaryUtils.toHex(signature));
return mutableRequest;
}
@Override
protected void addSessionCredentials(SdkHttpFullRequest.Builder mutableRequest,
AwsSessionCredentials credentials) {
mutableRequest.putHeader(SignerConstant.X_AMZ_SECURITY_TOKEN, credentials.sessionToken());
}
/**
* Calculate the hash of the request's payload. Subclass could override this
* method to provide different values for "x-amz-content-sha256" header or
* do any other necessary set-ups on the request headers. (e.g. aws-chunked
* uses a pre-defined header value, and needs to change some headers
* relating to content-encoding and content-length.)
*/
protected String calculateContentHash(SdkHttpFullRequest.Builder mutableRequest, T signerParams) {
return calculateContentHash(mutableRequest, signerParams, null);
}
/**
* This method overloads calculateContentHash with contentFlexibleChecksum.
* The contentFlexibleChecksum is computed at the same time while hash is calculated for Content.
*/
protected String calculateContentHash(SdkHttpFullRequest.Builder mutableRequest, T signerParams,
SdkChecksum contentFlexibleChecksum) {
InputStream payloadStream = getBinaryRequestPayloadStream(mutableRequest.contentStreamProvider());
return BinaryUtils.toHex(hash(payloadStream, contentFlexibleChecksum));
}
protected abstract void processRequestPayload(SdkHttpFullRequest.Builder mutableRequest,
byte[] signature,
byte[] signingKey,
Aws4SignerRequestParams signerRequestParams,
T signerParams);
protected abstract void processRequestPayload(SdkHttpFullRequest.Builder mutableRequest,
byte[] signature,
byte[] signingKey,
Aws4SignerRequestParams signerRequestParams,
T signerParams,
SdkChecksum sdkChecksum);
protected abstract String calculateContentHashPresign(SdkHttpFullRequest.Builder mutableRequest, U signerParams);
/**
* Step 3 of the AWS Signature version 4 calculation. It involves deriving
* the signing key and computing the signature. Refer to
* http://docs.aws.amazon
* .com/general/latest/gr/sigv4-calculate-signature.html
*/
protected final byte[] deriveSigningKey(AwsCredentials credentials, Aws4SignerRequestParams signerRequestParams) {
return deriveSigningKey(credentials,
Instant.ofEpochMilli(signerRequestParams.getRequestSigningDateTimeMilli()),
signerRequestParams.getRegionName(),
signerRequestParams.getServiceSigningName());
}
protected final byte[] deriveSigningKey(AwsCredentials credentials, Instant signingInstant, String region, String service) {
String cacheKey = createSigningCacheKeyName(credentials, region, service);
SignerKey signerKey = SIGNER_CACHE.get(cacheKey);
if (signerKey != null && signerKey.isValidForDate(signingInstant)) {
return signerKey.getSigningKey();
}
LOG.trace(() -> "Generating a new signing key as the signing key not available in the cache for the date: " +
signingInstant.toEpochMilli());
byte[] signingKey = newSigningKey(credentials,
Aws4SignerUtils.formatDateStamp(signingInstant),
region,
service);
SIGNER_CACHE.add(cacheKey, new SignerKey(signingInstant, signingKey));
return signingKey;
}
/**
* Step 1 of the AWS Signature version 4 calculation. Refer to
* http://docs.aws
* .amazon.com/general/latest/gr/sigv4-create-canonical-request.html to
* generate the canonical request.
*/
private CanonicalRequest createCanonicalRequest(SdkHttpFullRequest request,
SdkHttpFullRequest.Builder requestBuilder,
String contentSha256,
boolean doubleUrlEncode,
boolean normalizePath) {
return new CanonicalRequest(request, requestBuilder, contentSha256, doubleUrlEncode, normalizePath);
}
/**
* Step 2 of the AWS Signature version 4 calculation. Refer to
* http://docs.aws
* .amazon.com/general/latest/gr/sigv4-create-string-to-sign.html.
*/
private String createStringToSign(String canonicalRequest,
Aws4SignerRequestParams requestParams) {
LOG.debug(() -> "AWS4 Canonical Request: " + canonicalRequest);
String requestHash = BinaryUtils.toHex(hash(canonicalRequest));
String stringToSign = requestParams.getSigningAlgorithm() +
SignerConstant.LINE_SEPARATOR +
requestParams.getFormattedRequestSigningDateTime() +
SignerConstant.LINE_SEPARATOR +
requestParams.getScope() +
SignerConstant.LINE_SEPARATOR +
requestHash;
LOG.debug(() -> "AWS4 String to sign: " + stringToSign);
return stringToSign;
}
private String createSigningCacheKeyName(AwsCredentials credentials,
String regionName,
String serviceName) {
return credentials.secretAccessKey() + "-" + regionName + "-" + serviceName;
}
/**
* Step 3 of the AWS Signature version 4 calculation. It involves deriving
* the signing key and computing the signature. Refer to
* http://docs.aws.amazon
* .com/general/latest/gr/sigv4-calculate-signature.html
*/
private byte[] computeSignature(String stringToSign, byte[] signingKey) {
return sign(stringToSign.getBytes(StandardCharsets.UTF_8), signingKey,
SigningAlgorithm.HmacSHA256);
}
/**
* Creates the authorization header to be included in the request.
*/
private String buildAuthorizationHeader(byte[] signature,
AwsCredentials credentials,
Aws4SignerRequestParams signerParams,
CanonicalRequest canonicalRequest) {
String accessKeyId = credentials.accessKeyId();
String scope = signerParams.getScope();
StringBuilder stringBuilder = canonicalRequest.signedHeaderStringBuilder();
String signatureHex = BinaryUtils.toHex(signature);
return SignerConstant.AWS4_SIGNING_ALGORITHM
+ " Credential="
+ accessKeyId
+ "/"
+ scope
+ ", SignedHeaders="
+ stringBuilder
+ ", Signature="
+ signatureHex;
}
/**
* Includes all the signing headers as request parameters for pre-signing.
*/
private void addPreSignInformationToRequest(SdkHttpFullRequest.Builder mutableRequest,
CanonicalRequest canonicalRequest,
AwsCredentials sanitizedCredentials,
Aws4SignerRequestParams signerParams,
long expirationInSeconds) {
String signingCredentials = sanitizedCredentials.accessKeyId() + "/" + signerParams.getScope();
mutableRequest.putRawQueryParameter(SignerConstant.X_AMZ_ALGORITHM, SignerConstant.AWS4_SIGNING_ALGORITHM);
mutableRequest.putRawQueryParameter(SignerConstant.X_AMZ_DATE, signerParams.getFormattedRequestSigningDateTime());
mutableRequest.putRawQueryParameter(SignerConstant.X_AMZ_SIGNED_HEADER, canonicalRequest.signedHeaderString());
mutableRequest.putRawQueryParameter(SignerConstant.X_AMZ_EXPIRES, Long.toString(expirationInSeconds));
mutableRequest.putRawQueryParameter(SignerConstant.X_AMZ_CREDENTIAL, signingCredentials);
}
/**
* Tests a char to see if is it whitespace.
* This method considers the same characters to be white
* space as the Pattern class does when matching \s
*
* @param ch the character to be tested
* @return true if the character is white space, false otherwise.
*/
private static boolean isWhiteSpace(char ch) {
return ch == ' ' || ch == '\t' || ch == '\n' || ch == '\u000b' || ch == '\r' || ch == '\f';
}
private void addHostHeader(SdkHttpFullRequest.Builder mutableRequest) {
// AWS4 requires that we sign the Host header so we
// have to have it in the request by the time we sign.
StringBuilder hostHeaderBuilder = new StringBuilder(mutableRequest.host());
if (!SdkHttpUtils.isUsingStandardPort(mutableRequest.protocol(), mutableRequest.port())) {
hostHeaderBuilder.append(":").append(mutableRequest.port());
}
mutableRequest.putHeader(SignerConstant.HOST, hostHeaderBuilder.toString());
}
private void addDateHeader(SdkHttpFullRequest.Builder mutableRequest, String dateTime) {
mutableRequest.putHeader(SignerConstant.X_AMZ_DATE, dateTime);
}
/**
* Generates an expiration time for the presigned url. If user has specified
* an expiration time, check if it is in the given limit.
*/
private long getSignatureDurationInSeconds(Aws4SignerRequestParams requestParams,
U signingParams) {
long expirationInSeconds = signingParams.expirationTime()
.map(t -> t.getEpochSecond() -
(requestParams.getRequestSigningDateTimeMilli() / 1000))
.orElse(SignerConstant.PRESIGN_URL_MAX_EXPIRATION_SECONDS);
if (expirationInSeconds > SignerConstant.PRESIGN_URL_MAX_EXPIRATION_SECONDS) {
throw SdkClientException.builder()
.message("Requests that are pre-signed by SigV4 algorithm are valid for at most 7" +
" days. The expiration date set on the current request [" +
Aws4SignerUtils.formatTimestamp(expirationInSeconds * 1000L) + "] +" +
" has exceeded this limit.")
.build();
}
return expirationInSeconds;
}
/**
* Generates a new signing key from the given parameters and returns it.
*/
private byte[] newSigningKey(AwsCredentials credentials,
String dateStamp, String regionName, String serviceName) {
byte[] kSecret = ("AWS4" + credentials.secretAccessKey())
.getBytes(StandardCharsets.UTF_8);
byte[] kDate = sign(dateStamp, kSecret, SigningAlgorithm.HmacSHA256);
byte[] kRegion = sign(regionName, kDate, SigningAlgorithm.HmacSHA256);
byte[] kService = sign(serviceName, kRegion,
SigningAlgorithm.HmacSHA256);
return sign(SignerConstant.AWS4_TERMINATOR, kService, SigningAlgorithm.HmacSHA256);
}
protected <B extends Aws4PresignerParams.Builder> B extractPresignerParams(B builder,
ExecutionAttributes executionAttributes) {
builder = extractSignerParams(builder, executionAttributes);
builder.expirationTime(executionAttributes.getAttribute(AwsSignerExecutionAttribute.PRESIGNER_EXPIRATION));
return builder;
}
protected <B extends Aws4SignerParams.Builder> B extractSignerParams(B paramsBuilder,
ExecutionAttributes executionAttributes) {
paramsBuilder.awsCredentials(executionAttributes.getAttribute(AwsSignerExecutionAttribute.AWS_CREDENTIALS))
.signingName(executionAttributes.getAttribute(AwsSignerExecutionAttribute.SERVICE_SIGNING_NAME))
.signingRegion(executionAttributes.getAttribute(AwsSignerExecutionAttribute.SIGNING_REGION))
.timeOffset(executionAttributes.getAttribute(AwsSignerExecutionAttribute.TIME_OFFSET))
.signingClockOverride(executionAttributes.getAttribute(AwsSignerExecutionAttribute.SIGNING_CLOCK));
Boolean doubleUrlEncode = executionAttributes.getAttribute(AwsSignerExecutionAttribute.SIGNER_DOUBLE_URL_ENCODE);
if (doubleUrlEncode != null) {
paramsBuilder.doubleUrlEncode(doubleUrlEncode);
}
Boolean normalizePath =
executionAttributes.getAttribute(AwsSignerExecutionAttribute.SIGNER_NORMALIZE_PATH);
if (normalizePath != null) {
paramsBuilder.normalizePath(normalizePath);
}
ChecksumSpecs checksumSpecs = executionAttributes.getAttribute(RESOLVED_CHECKSUM_SPECS);
if (checksumSpecs != null && checksumSpecs.algorithm() != null) {
paramsBuilder.checksumParams(buildSignerChecksumParams(checksumSpecs));
}
return paramsBuilder;
}
private void putChecksumHeader(SignerChecksumParams checksumSigner, SdkChecksum sdkChecksum,
SdkHttpFullRequest.Builder mutableRequest, String contentHashString) {
if (checksumSigner != null && sdkChecksum != null && !UNSIGNED_PAYLOAD.equals(contentHashString)
&& !"STREAMING-UNSIGNED-PAYLOAD-TRAILER".equals(contentHashString)) {
if (HttpChecksumUtils.isHttpChecksumPresent(mutableRequest.build(),
ChecksumSpecs.builder()
.headerName(checksumSigner.checksumHeaderName()).build())) {
LOG.debug(() -> "Checksum already added in header ");
return;
}
String headerChecksum = checksumSigner.checksumHeaderName();
if (StringUtils.isNotBlank(headerChecksum)) {
mutableRequest.putHeader(headerChecksum,
BinaryUtils.toBase64(sdkChecksum.getChecksumBytes()));
}
}
}
private SignerChecksumParams buildSignerChecksumParams(ChecksumSpecs checksumSpecs) {
return SignerChecksumParams.builder().algorithm(checksumSpecs.algorithm())
.isStreamingRequest(checksumSpecs.isRequestStreaming())
.checksumHeaderName(checksumSpecs.headerName())
.build();
}
private SdkChecksum createSdkChecksumFromParams(T signingParams, SdkHttpFullRequest request) {
SignerChecksumParams signerChecksumParams = signingParams.checksumParams();
boolean isValidChecksumHeader =
signerChecksumParams != null && StringUtils.isNotBlank(signerChecksumParams.checksumHeaderName());
if (isValidChecksumHeader
&& !HttpChecksumUtils.isHttpChecksumPresent(
request,
ChecksumSpecs.builder().headerName(signerChecksumParams.checksumHeaderName()).build())) {
return SdkChecksum.forAlgorithm(signerChecksumParams.algorithm());
}
return null;
}
static final class CanonicalRequest {
private final SdkHttpFullRequest request;
private final SdkHttpFullRequest.Builder requestBuilder;
private final String contentSha256;
private final boolean doubleUrlEncode;
private final boolean normalizePath;
private String canonicalRequestString;
private StringBuilder signedHeaderStringBuilder;
private List<Pair<String, List<String>>> canonicalHeaders;
private String signedHeaderString;
CanonicalRequest(SdkHttpFullRequest request,
SdkHttpFullRequest.Builder requestBuilder,
String contentSha256,
boolean doubleUrlEncode,
boolean normalizePath) {
this.request = request;
this.requestBuilder = requestBuilder;
this.contentSha256 = contentSha256;
this.doubleUrlEncode = doubleUrlEncode;
this.normalizePath = normalizePath;
}
public String string() {
if (canonicalRequestString == null) {
StringBuilder canonicalRequest = new StringBuilder(512);
canonicalRequest.append(requestBuilder.method().toString())
.append(SignerConstant.LINE_SEPARATOR);
addCanonicalizedResourcePath(canonicalRequest,
request,
doubleUrlEncode,
normalizePath);
canonicalRequest.append(SignerConstant.LINE_SEPARATOR);
addCanonicalizedQueryString(canonicalRequest, requestBuilder);
canonicalRequest.append(SignerConstant.LINE_SEPARATOR);
addCanonicalizedHeaderString(canonicalRequest, canonicalHeaders());
canonicalRequest.append(SignerConstant.LINE_SEPARATOR)
.append(signedHeaderStringBuilder())
.append(SignerConstant.LINE_SEPARATOR)
.append(contentSha256);
this.canonicalRequestString = canonicalRequest.toString();
}
return canonicalRequestString;
}
private void addCanonicalizedResourcePath(StringBuilder result,
SdkHttpRequest request,
boolean urlEncode,
boolean normalizePath) {
String path = normalizePath ? request.getUri().normalize().getRawPath()
: request.encodedPath();
if (StringUtils.isEmpty(path)) {
result.append("/");
return;
}
if (urlEncode) {
path = SdkHttpUtils.urlEncodeIgnoreSlashes(path);
}
if (!path.startsWith("/")) {
result.append("/");
}
result.append(path);
// Normalization can leave a trailing slash at the end of the resource path,
// even if the input path doesn't end with one. Example input: /foo/bar/.
// Remove the trailing slash if the input path doesn't end with one.
boolean trimTrailingSlash = normalizePath &&
path.length() > 1 &&
!request.encodedPath().endsWith("/") &&
result.charAt(result.length() - 1) == '/';
if (trimTrailingSlash) {
result.setLength(result.length() - 1);
}
}
/**
* Examines the specified query string parameters and returns a
* canonicalized form.
* <p>
* The canonicalized query string is formed by first sorting all the query
* string parameters, then URI encoding both the key and value and then
* joining them, in order, separating key value pairs with an '&'.
*
* @return A canonicalized form for the specified query string parameters.
*/
private void addCanonicalizedQueryString(StringBuilder result, SdkHttpRequest.Builder httpRequest) {
SortedMap<String, List<String>> sorted = new TreeMap<>();
/**
* Signing protocol expects the param values also to be sorted after url
* encoding in addition to sorted parameter names.
*/
httpRequest.forEachRawQueryParameter((key, values) -> {
if (StringUtils.isEmpty(key)) {
// Do not sign empty keys.
return;
}
String encodedParamName = SdkHttpUtils.urlEncode(key);
List<String> encodedValues = new ArrayList<>(values.size());
for (String value : values) {
String encodedValue = SdkHttpUtils.urlEncode(value);
// Null values should be treated as empty for the purposes of signing, not missing.
// For example "?foo=" instead of "?foo".
String signatureFormattedEncodedValue = encodedValue == null ? "" : encodedValue;
encodedValues.add(signatureFormattedEncodedValue);
}
Collections.sort(encodedValues);
sorted.put(encodedParamName, encodedValues);
});
SdkHttpUtils.flattenQueryParameters(result, sorted);
}
public StringBuilder signedHeaderStringBuilder() {
if (signedHeaderStringBuilder == null) {
signedHeaderStringBuilder = new StringBuilder();
addSignedHeaders(signedHeaderStringBuilder, canonicalHeaders());
}
return signedHeaderStringBuilder;
}
public String signedHeaderString() {
if (signedHeaderString == null) {
this.signedHeaderString = signedHeaderStringBuilder().toString();
}
return signedHeaderString;
}
private List<Pair<String, List<String>>> canonicalHeaders() {
if (canonicalHeaders == null) {
canonicalHeaders = canonicalizeSigningHeaders(requestBuilder);
}
return canonicalHeaders;
}
private void addCanonicalizedHeaderString(StringBuilder result, List<Pair<String, List<String>>> canonicalizedHeaders) {
canonicalizedHeaders.forEach(header -> {
result.append(header.left());
result.append(":");
for (String headerValue : header.right()) {
addAndTrim(result, headerValue);
result.append(",");
}
result.setLength(result.length() - 1);
result.append("\n");
});
}
private List<Pair<String, List<String>>> canonicalizeSigningHeaders(SdkHttpFullRequest.Builder headers) {
List<Pair<String, List<String>>> result = new ArrayList<>(headers.numHeaders());
headers.forEachHeader((key, value) -> {
String lowerCaseHeader = lowerCase(key);
if (!LIST_OF_HEADERS_TO_IGNORE_IN_LOWER_CASE.contains(lowerCaseHeader)) {
result.add(Pair.of(lowerCaseHeader, value));
}
});
result.sort(Comparator.comparing(Pair::left));
return result;
}
/**
* "The addAndTrim function removes excess white space before and after values,
* and converts sequential spaces to a single space."
* <p>
* https://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html
* <p>
* The collapse-whitespace logic is equivalent to:
* <pre>
* value.replaceAll("\\s+", " ")
* </pre>
* but does not create a Pattern object that needs to compile the match
* string; it also prevents us from having to make a Matcher object as well.
*/
private void addAndTrim(StringBuilder result, String value) {
int lengthBefore = result.length();
boolean isStart = true;
boolean previousIsWhiteSpace = false;
for (int i = 0; i < value.length(); i++) {
char ch = value.charAt(i);
if (isWhiteSpace(ch)) {
if (previousIsWhiteSpace || isStart) {
continue;
}
result.append(' ');
previousIsWhiteSpace = true;
} else {
result.append(ch);
isStart = false;
previousIsWhiteSpace = false;
}
}
if (lengthBefore == result.length()) {
return;
}
int lastNonWhitespaceChar = result.length() - 1;
while (isWhiteSpace(result.charAt(lastNonWhitespaceChar))) {
--lastNonWhitespaceChar;
}
result.setLength(lastNonWhitespaceChar + 1);
}
private void addSignedHeaders(StringBuilder result, List<Pair<String, List<String>>> canonicalizedHeaders) {
for (Pair<String, List<String>> header : canonicalizedHeaders) {
result.append(header.left()).append(';');
}
if (!canonicalizedHeaders.isEmpty()) {
result.setLength(result.length() - 1);
}
}
}
}
| 1,720 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer/internal/FifoCache.java | /*
* 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.auth.signer.internal;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock.ReadLock;
import java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.annotations.ThreadSafe;
/**
* A bounded cache that has a FIFO eviction policy when the cache is full.
*
* @param <T>
* value type
*/
@ThreadSafe
@SdkInternalApi
public final class FifoCache<T> {
private final BoundedLinkedHashMap<String, T> map;
private final ReadLock rlock;
private final WriteLock wlock;
/**
* @param maxSize
* the maximum number of entries of the cache
*/
public FifoCache(final int maxSize) {
if (maxSize < 1) {
throw new IllegalArgumentException("maxSize " + maxSize
+ " must be at least 1");
}
map = new BoundedLinkedHashMap<>(maxSize);
ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
rlock = lock.readLock();
wlock = lock.writeLock();
}
/**
* Adds an entry to the cache, evicting the earliest entry if necessary.
*/
public T add(String key, T value) {
wlock.lock();
try {
return map.put(key, value);
} finally {
wlock.unlock();
}
}
/** Returns the value of the given key; or null of no such entry exists. */
public T get(String key) {
rlock.lock();
try {
return map.get(key);
} finally {
rlock.unlock();
}
}
/**
* Returns the current size of the cache.
*/
public int size() {
rlock.lock();
try {
return map.size();
} finally {
rlock.unlock();
}
}
/**
* Returns the maximum size of the cache.
*/
public int getMaxSize() {
return map.getMaxSize();
}
@Override
public String toString() {
rlock.lock();
try {
return map.toString();
} finally {
rlock.unlock();
}
}
}
| 1,721 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer/internal/AbstractAwsSigner.java | /*
* 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.auth.signer.internal;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.AwsCredentials;
import software.amazon.awssdk.auth.credentials.AwsSessionCredentials;
import software.amazon.awssdk.core.checksums.SdkChecksum;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.core.io.SdkDigestInputStream;
import software.amazon.awssdk.core.signer.Signer;
import software.amazon.awssdk.http.ContentStreamProvider;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.utils.BinaryUtils;
import software.amazon.awssdk.utils.StringUtils;
/**
* Abstract base class for AWS signing protocol implementations. Provides
* utilities commonly needed by signing protocols such as computing
* canonicalized host names, query string parameters, etc.
* <p>
* Not intended to be sub-classed by developers.
*/
@SdkInternalApi
public abstract class AbstractAwsSigner implements Signer {
private static final ThreadLocal<MessageDigest> SHA256_MESSAGE_DIGEST;
static {
SHA256_MESSAGE_DIGEST = ThreadLocal.withInitial(() -> {
try {
return MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException e) {
throw SdkClientException.builder()
.message("Unable to get SHA256 Function" + e.getMessage())
.cause(e)
.build();
}
});
}
private static byte[] doHash(String text) throws SdkClientException {
try {
MessageDigest md = getMessageDigestInstance();
md.update(text.getBytes(StandardCharsets.UTF_8));
return md.digest();
} catch (Exception e) {
throw SdkClientException.builder()
.message("Unable to compute hash while signing request: " + e.getMessage())
.cause(e)
.build();
}
}
/**
* Returns the re-usable thread local version of MessageDigest.
*/
private static MessageDigest getMessageDigestInstance() {
MessageDigest messageDigest = SHA256_MESSAGE_DIGEST.get();
messageDigest.reset();
return messageDigest;
}
/**
* Computes an RFC 2104-compliant HMAC signature and returns the result as a
* Base64 encoded string.
*/
protected String signAndBase64Encode(String data, String key,
SigningAlgorithm algorithm) throws SdkClientException {
return signAndBase64Encode(data.getBytes(StandardCharsets.UTF_8), key, algorithm);
}
/**
* Computes an RFC 2104-compliant HMAC signature for an array of bytes and
* returns the result as a Base64 encoded string.
*/
private String signAndBase64Encode(byte[] data, String key,
SigningAlgorithm algorithm) throws SdkClientException {
try {
byte[] signature = sign(data, key.getBytes(StandardCharsets.UTF_8), algorithm);
return BinaryUtils.toBase64(signature);
} catch (Exception e) {
throw SdkClientException.builder()
.message("Unable to calculate a request signature: " + e.getMessage())
.cause(e)
.build();
}
}
protected byte[] signWithMac(String stringData, Mac mac) {
try {
return mac.doFinal(stringData.getBytes(StandardCharsets.UTF_8));
} catch (Exception e) {
throw SdkClientException.builder()
.message("Unable to calculate a request signature: " + e.getMessage())
.cause(e)
.build();
}
}
protected byte[] sign(String stringData, byte[] key,
SigningAlgorithm algorithm) throws SdkClientException {
try {
byte[] data = stringData.getBytes(StandardCharsets.UTF_8);
return sign(data, key, algorithm);
} catch (Exception e) {
throw SdkClientException.builder()
.message("Unable to calculate a request signature: " + e.getMessage())
.cause(e)
.build();
}
}
protected byte[] sign(byte[] data, byte[] key, SigningAlgorithm algorithm) throws SdkClientException {
try {
Mac mac = algorithm.getMac();
mac.init(new SecretKeySpec(key, algorithm.toString()));
return mac.doFinal(data);
} catch (Exception e) {
throw SdkClientException.builder()
.message("Unable to calculate a request signature: " + e.getMessage())
.cause(e)
.build();
}
}
/**
* Hashes the string contents (assumed to be UTF-8) using the SHA-256
* algorithm.
*
* @param text The string to hash.
* @return The hashed bytes from the specified string.
* @throws SdkClientException If the hash cannot be computed.
*/
static byte[] hash(String text) throws SdkClientException {
return AbstractAwsSigner.doHash(text);
}
byte[] hash(InputStream input, SdkChecksum sdkChecksum) throws SdkClientException {
try {
MessageDigest md = getMessageDigestInstance();
@SuppressWarnings("resource")
DigestInputStream digestInputStream = new SdkDigestInputStream(
input, md, sdkChecksum);
byte[] buffer = new byte[1024];
while (digestInputStream.read(buffer) > -1) {
;
}
return digestInputStream.getMessageDigest().digest();
} catch (Exception e) {
throw SdkClientException.builder()
.message("Unable to compute hash while signing request: " + e.getMessage())
.cause(e)
.build();
}
}
/**
* Hashes the binary data using the SHA-256 algorithm.
*
* @param data The binary data to hash.
* @param sdkChecksum Checksum Instance which gets updated as data is read while hashing.
* @return The hashed bytes from the specified data.
* @throws SdkClientException If the hash cannot be computed.
*/
byte[] hash(byte[] data, SdkChecksum sdkChecksum) throws SdkClientException {
try {
MessageDigest md = getMessageDigestInstance();
md.update(data);
if (sdkChecksum != null) {
sdkChecksum.update(data);
}
return md.digest();
} catch (Exception e) {
throw SdkClientException.builder()
.message("Unable to compute hash while signing request: " + e.getMessage())
.cause(e)
.build();
}
}
/**
* Hashes the binary data using the SHA-256 algorithm.
*
* @param data The binary data to hash.
* @return The hashed bytes from the specified data.
* @throws SdkClientException If the hash cannot be computed.
*/
byte[] hash(byte[] data) throws SdkClientException {
return hash(data, null);
}
protected InputStream getBinaryRequestPayloadStream(ContentStreamProvider streamProvider) {
try {
if (streamProvider == null) {
return new ByteArrayInputStream(new byte[0]);
}
return streamProvider.newStream();
} catch (SdkClientException e) {
throw e;
} catch (Exception e) {
throw SdkClientException.builder()
.message("Unable to read request payload to sign request: " + e.getMessage())
.cause(e)
.build();
}
}
/**
* Loads the individual access key ID and secret key from the specified credentials, trimming any extra whitespace from the
* credentials.
*
* <p>Returns either a {@link AwsSessionCredentials} or a {@link AwsBasicCredentials} object, depending on the input type.
*
* @return A new credentials object with the sanitized credentials.
*/
protected AwsCredentials sanitizeCredentials(AwsCredentials credentials) {
String accessKeyId = StringUtils.trim(credentials.accessKeyId());
String secretKey = StringUtils.trim(credentials.secretAccessKey());
if (credentials instanceof AwsSessionCredentials) {
AwsSessionCredentials sessionCredentials = (AwsSessionCredentials) credentials;
return AwsSessionCredentials.create(accessKeyId,
secretKey,
StringUtils.trim(sessionCredentials.sessionToken()));
}
return AwsBasicCredentials.create(accessKeyId, secretKey);
}
/**
* Adds session credentials to the request given.
*
* @param mutableRequest The request to add session credentials information to
* @param credentials The session credentials to add to the request
*/
protected abstract void addSessionCredentials(SdkHttpFullRequest.Builder mutableRequest,
AwsSessionCredentials credentials);
}
| 1,722 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer/internal/DigestComputingSubscriber.java | /*
* 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.auth.signer.internal;
import java.nio.ByteBuffer;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CompletableFuture;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.core.checksums.SdkChecksum;
import software.amazon.awssdk.core.exception.SdkClientException;
@SdkInternalApi
public final class DigestComputingSubscriber implements Subscriber<ByteBuffer> {
private final CompletableFuture<byte[]> digestBytes = new CompletableFuture<>();
private final MessageDigest messageDigest;
private volatile boolean canceled = false;
private volatile Subscription subscription;
private final SdkChecksum sdkChecksum;
public DigestComputingSubscriber(MessageDigest messageDigest, SdkChecksum sdkChecksum) {
this.messageDigest = messageDigest;
this.sdkChecksum = sdkChecksum;
digestBytes.whenComplete((r, t) -> {
if (t instanceof CancellationException) {
synchronized (DigestComputingSubscriber.this) {
canceled = true;
if (subscription != null) {
subscription.cancel();
}
}
}
});
}
@Override
public void onSubscribe(Subscription subscription) {
synchronized (this) {
if (!canceled) {
this.subscription = subscription;
subscription.request(Long.MAX_VALUE);
} else {
subscription.cancel();
}
}
}
@Override
public void onNext(ByteBuffer byteBuffer) {
if (!canceled) {
if (this.sdkChecksum != null) {
// check using flip
ByteBuffer duplicate = byteBuffer.duplicate();
sdkChecksum.update(duplicate);
}
messageDigest.update(byteBuffer);
}
}
@Override
public void onError(Throwable throwable) {
digestBytes.completeExceptionally(throwable);
}
@Override
public void onComplete() {
digestBytes.complete(messageDigest.digest());
}
public CompletableFuture<byte[]> digestBytes() {
return digestBytes;
}
public static DigestComputingSubscriber forSha256() {
try {
return new DigestComputingSubscriber(MessageDigest.getInstance("SHA-256"), null);
} catch (NoSuchAlgorithmException e) {
throw SdkClientException.create("Unable to create SHA-256 computing subscriber", e);
}
}
public static DigestComputingSubscriber forSha256(SdkChecksum sdkChecksum) {
try {
return new DigestComputingSubscriber(MessageDigest.getInstance("SHA-256"), sdkChecksum);
} catch (NoSuchAlgorithmException e) {
throw SdkClientException.create("Unable to create SHA-256 computing subscriber", e);
}
}
}
| 1,723 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer/internal/SignerKey.java | /*
* 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.auth.signer.internal;
import java.time.Instant;
import software.amazon.awssdk.annotations.Immutable;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.utils.DateUtils;
/**
* Holds the signing key and the number of days since epoch for the date for
* which the signing key was generated.
*/
@Immutable
@SdkInternalApi
public final class SignerKey {
private final long daysSinceEpoch;
private final byte[] signingKey;
public SignerKey(Instant date, byte[] signingKey) {
if (date == null) {
throw new IllegalArgumentException(
"Not able to cache signing key. Signing date to be is null");
}
if (signingKey == null) {
throw new IllegalArgumentException(
"Not able to cache signing key. Signing Key to be cached are null");
}
this.daysSinceEpoch = DateUtils.numberOfDaysSinceEpoch(date.toEpochMilli());
this.signingKey = signingKey.clone();
}
public boolean isValidForDate(Instant other) {
return daysSinceEpoch == DateUtils.numberOfDaysSinceEpoch(other.toEpochMilli());
}
/**
* Returns a copy of the signing key.
*/
public byte[] getSigningKey() {
return signingKey.clone();
}
}
| 1,724 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer/internal/Aws4SignerUtils.java | /*
* 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.auth.signer.internal;
import java.io.IOException;
import java.io.InputStream;
import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.http.Header;
import software.amazon.awssdk.http.SdkHttpFullRequest;
/**
* Utility methods that is used by the different AWS Signer implementations.
* This class is strictly internal and is subjected to change.
*/
@SdkInternalApi
public final class Aws4SignerUtils {
private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter
.ofPattern("yyyyMMdd").withZone(ZoneId.of("UTC"));
private static final DateTimeFormatter TIME_FORMATTER = DateTimeFormatter
.ofPattern("yyyyMMdd'T'HHmmss'Z'").withZone(ZoneId.of("UTC"));
private Aws4SignerUtils() {
}
/**
* Returns a string representation of the given date time in yyyyMMdd
* format. The date returned is in the UTC zone.
*
* For example, given a time "1416863450581", this method returns "20141124"
*/
public static String formatDateStamp(long timeMilli) {
return DATE_FORMATTER.format(Instant.ofEpochMilli(timeMilli));
}
public static String formatDateStamp(Instant instant) {
return DATE_FORMATTER.format(instant);
}
/**
* Returns a string representation of the given date time in
* yyyyMMdd'T'HHmmss'Z' format. The date returned is in the UTC zone.
*
* For example, given a time "1416863450581", this method returns
* "20141124T211050Z"
*/
public static String formatTimestamp(long timeMilli) {
return TIME_FORMATTER.format(Instant.ofEpochMilli(timeMilli));
}
public static String formatTimestamp(Instant instant) {
return TIME_FORMATTER.format(instant);
}
/**
* Calculates the content length of a request. If the content-length isn't in the header,
* the method reads the whole input stream to get the length.
*/
public static long calculateRequestContentLength(SdkHttpFullRequest.Builder mutableRequest) {
String contentLength = mutableRequest.firstMatchingHeader(Header.CONTENT_LENGTH)
.orElse(null);
long originalContentLength;
if (contentLength != null) {
originalContentLength = Long.parseLong(contentLength);
} else {
try {
originalContentLength = getContentLength(mutableRequest.contentStreamProvider().newStream());
} catch (IOException e) {
throw SdkClientException.builder()
.message("Cannot get the content-length of the request content.")
.cause(e)
.build();
}
}
return originalContentLength;
}
/**
* Read a stream to get the length.
*/
private static long getContentLength(InputStream content) throws IOException {
long contentLength = 0;
byte[] tmp = new byte[4096];
int read;
while ((read = content.read(tmp)) != -1) {
contentLength += read;
}
return contentLength;
}
}
| 1,725 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer/internal/BaseEventStreamAsyncAws4Signer.java | /*
* 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.auth.signer.internal;
import static software.amazon.awssdk.auth.signer.internal.SignerConstant.X_AMZ_CONTENT_SHA256;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Optional;
import java.util.TreeMap;
import java.util.function.Function;
import org.reactivestreams.Publisher;
import org.reactivestreams.Subscriber;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.auth.credentials.AwsCredentials;
import software.amazon.awssdk.auth.signer.params.Aws4SignerParams;
import software.amazon.awssdk.core.async.AsyncRequestBody;
import software.amazon.awssdk.core.async.SdkPublisher;
import software.amazon.awssdk.core.checksums.SdkChecksum;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.utils.BinaryUtils;
import software.amazon.awssdk.utils.Logger;
import software.amazon.eventstream.HeaderValue;
import software.amazon.eventstream.Message;
@SdkInternalApi
public abstract class BaseEventStreamAsyncAws4Signer extends BaseAsyncAws4Signer {
//Constants for event stream headers
public static final String EVENT_STREAM_SIGNATURE = ":chunk-signature";
public static final String EVENT_STREAM_DATE = ":date";
private static final Logger LOG = Logger.loggerFor(BaseEventStreamAsyncAws4Signer.class);
private static final String HTTP_CONTENT_SHA_256 = "STREAMING-AWS4-HMAC-SHA256-EVENTS";
private static final String EVENT_STREAM_PAYLOAD = "AWS4-HMAC-SHA256-PAYLOAD";
private static final int PAYLOAD_TRUNCATE_LENGTH = 32;
protected BaseEventStreamAsyncAws4Signer() {
}
@Override
public SdkHttpFullRequest sign(SdkHttpFullRequest request, ExecutionAttributes executionAttributes) {
request = addContentSha256Header(request);
return super.sign(request, executionAttributes);
}
@Override
public SdkHttpFullRequest sign(SdkHttpFullRequest request, Aws4SignerParams signingParams) {
request = addContentSha256Header(request);
return super.sign(request, signingParams);
}
@Override
protected AsyncRequestBody transformRequestProvider(String headerSignature,
Aws4SignerRequestParams signerRequestParams,
Aws4SignerParams signerParams,
AsyncRequestBody asyncRequestBody) {
/**
* Concat trailing empty frame to publisher
*/
Publisher<ByteBuffer> publisherWithTrailingEmptyFrame = appendEmptyFrame(asyncRequestBody);
/**
* Map publisher with signing function
*/
Publisher<ByteBuffer> publisherWithSignedFrame =
transformRequestBodyPublisher(publisherWithTrailingEmptyFrame, headerSignature,
signerParams.awsCredentials(), signerRequestParams);
AsyncRequestBody transformedRequestBody = AsyncRequestBody.fromPublisher(publisherWithSignedFrame);
return new SigningRequestBodyProvider(transformedRequestBody);
}
/**
* Returns the pre-defined header value and set other necessary headers if
* the request needs to be chunk-encoded. Otherwise calls the superclass
* method which calculates the hash of the whole content for signing.
*/
@Override
protected String calculateContentHash(SdkHttpFullRequest.Builder mutableRequest, Aws4SignerParams signerParams,
SdkChecksum contentFlexibleChecksum) {
return HTTP_CONTENT_SHA_256;
}
private static Publisher<ByteBuffer> appendEmptyFrame(Publisher<ByteBuffer> publisher) {
return s -> {
Subscriber<ByteBuffer> adaptedSubscriber = new AsyncSigV4SubscriberAdapter(s);
publisher.subscribe(adaptedSubscriber);
};
}
private Publisher<ByteBuffer> transformRequestBodyPublisher(Publisher<ByteBuffer> publisher, String headerSignature,
AwsCredentials credentials,
Aws4SignerRequestParams signerRequestParams) {
return SdkPublisher.adapt(publisher)
.map(getDataFrameSigner(headerSignature, credentials, signerRequestParams));
}
private Function<ByteBuffer, ByteBuffer> getDataFrameSigner(String headerSignature,
AwsCredentials credentials,
Aws4SignerRequestParams signerRequestParams) {
return new Function<ByteBuffer, ByteBuffer>() {
final Aws4SignerRequestParams requestParams = signerRequestParams;
/**
* Initiate rolling signature with header signature
*/
String priorSignature = headerSignature;
@Override
public ByteBuffer apply(ByteBuffer byteBuffer) {
/**
* Signing Date
*/
Map<String, HeaderValue> nonSignatureHeaders = new HashMap<>();
Instant signingInstant = requestParams.getSigningClock().instant();
nonSignatureHeaders.put(EVENT_STREAM_DATE, HeaderValue.fromTimestamp(signingInstant));
/**
* Derive Signing Key
*/
AwsCredentials sanitizedCredentials = sanitizeCredentials(credentials);
byte[] signingKey = deriveSigningKey(sanitizedCredentials,
signingInstant,
requestParams.getRegionName(),
requestParams.getServiceSigningName());
/**
* Calculate rolling signature
*/
byte[] payload = byteBuffer.array();
byte[] signatureBytes = signEventStream(priorSignature, signingKey, signingInstant, requestParams,
nonSignatureHeaders, payload);
priorSignature = BinaryUtils.toHex(signatureBytes);
/**
* Add signing layer event-stream headers
*/
Map<String, HeaderValue> headers = new HashMap<>(nonSignatureHeaders);
//Signature headers
headers.put(EVENT_STREAM_SIGNATURE, HeaderValue.fromByteArray(signatureBytes));
/**
* Encode signed event to byte
*/
Message signedMessage = new Message(sortHeaders(headers), payload);
if (LOG.isLoggingLevelEnabled("trace")) {
LOG.trace(() -> "Signed message: " + toDebugString(signedMessage, false));
} else {
LOG.debug(() -> "Signed message: " + toDebugString(signedMessage, true));
}
return signedMessage.toByteBuffer();
}
};
}
/**
* Sign event stream with SigV4 signature
*
* @param priorSignature signature of previous frame (Header frame is the 0th frame)
* @param signingKey derived signing key
* @param signingInstant the instant at which this message is being signed
* @param requestParams request parameters
* @param nonSignatureHeaders non-signature headers
* @param payload event stream payload
* @return encoded event with signature
*/
private byte[] signEventStream(
String priorSignature,
byte[] signingKey,
Instant signingInstant,
Aws4SignerRequestParams requestParams,
Map<String, HeaderValue> nonSignatureHeaders,
byte[] payload) {
// String to sign
String stringToSign =
EVENT_STREAM_PAYLOAD +
SignerConstant.LINE_SEPARATOR +
Aws4SignerUtils.formatTimestamp(signingInstant) +
SignerConstant.LINE_SEPARATOR +
computeScope(signingInstant, requestParams) +
SignerConstant.LINE_SEPARATOR +
priorSignature +
SignerConstant.LINE_SEPARATOR +
BinaryUtils.toHex(hash(Message.encodeHeaders(sortHeaders(nonSignatureHeaders).entrySet()))) +
SignerConstant.LINE_SEPARATOR +
BinaryUtils.toHex(hash(payload));
// calculate signature
return sign(stringToSign.getBytes(StandardCharsets.UTF_8), signingKey,
SigningAlgorithm.HmacSHA256);
}
private String computeScope(Instant signingInstant, Aws4SignerRequestParams requestParams) {
return Aws4SignerUtils.formatDateStamp(signingInstant) + "/" +
requestParams.getRegionName() + "/" +
requestParams.getServiceSigningName() + "/" +
SignerConstant.AWS4_TERMINATOR;
}
/**
* Sort headers in alphabetic order, with exception that EVENT_STREAM_SIGNATURE header always at last
*
* @param headers unsorted headers
* @return sorted headers
*/
private TreeMap<String, HeaderValue> sortHeaders(Map<String, HeaderValue> headers) {
TreeMap<String, HeaderValue> sortedHeaders = new TreeMap<>((header1, header2) -> {
// signature header should always be the last header
if (header1.equals(EVENT_STREAM_SIGNATURE)) {
return 1; // put header1 at last
} else if (header2.equals(EVENT_STREAM_SIGNATURE)) {
return -1; // put header2 at last
} else {
return header1.compareTo(header2);
}
});
sortedHeaders.putAll(headers);
return sortedHeaders;
}
private SdkHttpFullRequest addContentSha256Header(SdkHttpFullRequest request) {
return request.toBuilder()
.putHeader(X_AMZ_CONTENT_SHA256, "STREAMING-AWS4-HMAC-SHA256-EVENTS").build();
}
/**
* {@link AsyncRequestBody} implementation that use the provider that signs the events.
* Using anonymous class raises spot bug violation
*/
private static class SigningRequestBodyProvider implements AsyncRequestBody {
private AsyncRequestBody transformedRequestBody;
SigningRequestBodyProvider(AsyncRequestBody transformedRequestBody) {
this.transformedRequestBody = transformedRequestBody;
}
@Override
public void subscribe(Subscriber<? super ByteBuffer> s) {
transformedRequestBody.subscribe(s);
}
@Override
public Optional<Long> contentLength() {
return transformedRequestBody.contentLength();
}
@Override
public String contentType() {
return transformedRequestBody.contentType();
}
}
static String toDebugString(Message m, boolean truncatePayload) {
StringBuilder sb = new StringBuilder("Message = {headers={");
Map<String, HeaderValue> headers = m.getHeaders();
Iterator<Map.Entry<String, HeaderValue>> headersIter = headers.entrySet().iterator();
while (headersIter.hasNext()) {
Map.Entry<String, HeaderValue> h = headersIter.next();
sb.append(h.getKey()).append("={").append(h.getValue().toString()).append("}");
if (headersIter.hasNext()) {
sb.append(", ");
}
}
sb.append("}, payload=");
byte[] payload = m.getPayload();
byte[] payloadToLog;
// We don't actually need to truncate if the payload length is already within the truncate limit
truncatePayload = truncatePayload && payload.length > PAYLOAD_TRUNCATE_LENGTH;
if (truncatePayload) {
// Would be nice if BinaryUtils.toHex() could take an array index range instead so we don't need to copy
payloadToLog = Arrays.copyOf(payload, PAYLOAD_TRUNCATE_LENGTH);
} else {
payloadToLog = payload;
}
sb.append(BinaryUtils.toHex(payloadToLog));
if (truncatePayload) {
sb.append("...");
}
sb.append("}");
return sb.toString();
}
}
| 1,726 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer/internal/BaseAws4Signer.java | /*
* 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.auth.signer.internal;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.auth.credentials.CredentialUtils;
import software.amazon.awssdk.auth.signer.params.Aws4PresignerParams;
import software.amazon.awssdk.auth.signer.params.Aws4SignerParams;
import software.amazon.awssdk.core.checksums.SdkChecksum;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.http.SdkHttpFullRequest;
/**
* Abstract base class for concrete implementations of Aws4 signers.
*/
@SdkInternalApi
public abstract class BaseAws4Signer extends AbstractAws4Signer<Aws4SignerParams, Aws4PresignerParams> {
@Override
public SdkHttpFullRequest sign(SdkHttpFullRequest request, ExecutionAttributes executionAttributes) {
Aws4SignerParams signingParams = extractSignerParams(Aws4SignerParams.builder(), executionAttributes)
.build();
return sign(request, signingParams);
}
public SdkHttpFullRequest sign(SdkHttpFullRequest request, Aws4SignerParams signingParams) {
// anonymous credentials, don't sign
if (CredentialUtils.isAnonymous(signingParams.awsCredentials())) {
return request;
}
Aws4SignerRequestParams requestParams = new Aws4SignerRequestParams(signingParams);
return doSign(request, requestParams, signingParams).build();
}
@Override
public SdkHttpFullRequest presign(SdkHttpFullRequest requestToSign, ExecutionAttributes executionAttributes) {
Aws4PresignerParams signingParams = extractPresignerParams(Aws4PresignerParams.builder(),
executionAttributes)
.build();
return presign(requestToSign, signingParams);
}
public SdkHttpFullRequest presign(SdkHttpFullRequest request, Aws4PresignerParams signingParams) {
// anonymous credentials, don't sign
if (CredentialUtils.isAnonymous(signingParams.awsCredentials())) {
return request;
}
Aws4SignerRequestParams requestParams = new Aws4SignerRequestParams(signingParams);
return doPresign(request, requestParams, signingParams).build();
}
/**
* Subclass could override this method to perform any additional procedure
* on the request payload, with access to the result from signing the
* header. (e.g. Signing the payload by chunk-encoding). The default
* implementation doesn't need to do anything.
*/
@Override
protected void processRequestPayload(SdkHttpFullRequest.Builder mutableRequest,
byte[] signature,
byte[] signingKey,
Aws4SignerRequestParams signerRequestParams,
Aws4SignerParams signerParams) {
processRequestPayload(mutableRequest, signature, signingKey,
signerRequestParams, signerParams, null);
}
/**
* This method overloads processRequestPayload with sdkChecksum.
* The sdkChecksum if passed, is computed while processing request payload.
*/
@Override
protected void processRequestPayload(SdkHttpFullRequest.Builder mutableRequest,
byte[] signature,
byte[] signingKey,
Aws4SignerRequestParams signerRequestParams,
Aws4SignerParams signerParams,
SdkChecksum sdkChecksum) {
}
/**
* Calculate the hash of the request's payload. In case of pre-sign, the
* existing code would generate the hash of an empty byte array and returns
* it. This method can be overridden by sub classes to provide different
* values (e.g) For S3 pre-signing, the content hash calculation is
* different from the general implementation.
*/
@Override
protected String calculateContentHashPresign(SdkHttpFullRequest.Builder mutableRequest,
Aws4PresignerParams signerParams) {
return calculateContentHash(mutableRequest, signerParams);
}
}
| 1,727 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer/internal/AbstractAwsS3V4Signer.java | /*
* 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.auth.signer.internal;
import static software.amazon.awssdk.auth.signer.internal.Aws4SignerUtils.calculateRequestContentLength;
import static software.amazon.awssdk.auth.signer.internal.SignerConstant.X_AMZ_CONTENT_SHA256;
import java.io.InputStream;
import java.util.Optional;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.auth.credentials.CredentialUtils;
import software.amazon.awssdk.auth.signer.S3SignerExecutionAttribute;
import software.amazon.awssdk.auth.signer.internal.chunkedencoding.AwsS3V4ChunkSigner;
import software.amazon.awssdk.auth.signer.internal.chunkedencoding.AwsSignedChunkedEncodingInputStream;
import software.amazon.awssdk.auth.signer.params.Aws4PresignerParams;
import software.amazon.awssdk.auth.signer.params.AwsS3V4SignerParams;
import software.amazon.awssdk.core.checksums.ChecksumSpecs;
import software.amazon.awssdk.core.checksums.SdkChecksum;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.core.internal.chunked.AwsChunkedEncodingConfig;
import software.amazon.awssdk.core.internal.util.HttpChecksumUtils;
import software.amazon.awssdk.http.ContentStreamProvider;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.utils.BinaryUtils;
import software.amazon.awssdk.utils.StringUtils;
/**
* AWS4 signer implementation for AWS S3
*/
@SdkInternalApi
public abstract class AbstractAwsS3V4Signer extends AbstractAws4Signer<AwsS3V4SignerParams, Aws4PresignerParams> {
public static final String CONTENT_SHA_256_WITH_CHECKSUM = "STREAMING-AWS4-HMAC-SHA256-PAYLOAD-TRAILER";
public static final String STREAMING_UNSIGNED_PAYLOAD_TRAILER = "STREAMING-UNSIGNED-PAYLOAD-TRAILER";
private static final String CONTENT_SHA_256 = "STREAMING-AWS4-HMAC-SHA256-PAYLOAD";
/**
* Sent to S3 in lieu of a payload hash when unsigned payloads are enabled
*/
private static final String UNSIGNED_PAYLOAD = "UNSIGNED-PAYLOAD";
private static final String CONTENT_LENGTH = "Content-Length";
@Override
public SdkHttpFullRequest sign(SdkHttpFullRequest request, ExecutionAttributes executionAttributes) {
AwsS3V4SignerParams signingParams = constructAwsS3SignerParams(executionAttributes);
return sign(request, signingParams);
}
/**
* A method to sign the given #request. The parameters required for signing are provided through the modeled
* {@link AbstractAwsS3V4Signer} class.
*
* @param request The request to sign
* @param signingParams Class with the parameters used for signing the request
* @return A signed version of the input request
*/
public SdkHttpFullRequest sign(SdkHttpFullRequest request, AwsS3V4SignerParams signingParams) {
// anonymous credentials, don't sign
if (CredentialUtils.isAnonymous(signingParams.awsCredentials())) {
return request;
}
Aws4SignerRequestParams requestParams = new Aws4SignerRequestParams(signingParams);
return doSign(request, requestParams, signingParams).build();
}
private AwsS3V4SignerParams constructAwsS3SignerParams(ExecutionAttributes executionAttributes) {
AwsS3V4SignerParams.Builder signerParams = extractSignerParams(AwsS3V4SignerParams.builder(),
executionAttributes);
Optional.ofNullable(executionAttributes.getAttribute(S3SignerExecutionAttribute.ENABLE_CHUNKED_ENCODING))
.ifPresent(signerParams::enableChunkedEncoding);
Optional.ofNullable(executionAttributes.getAttribute(S3SignerExecutionAttribute.ENABLE_PAYLOAD_SIGNING))
.ifPresent(signerParams::enablePayloadSigning);
return signerParams.build();
}
@Override
public SdkHttpFullRequest presign(SdkHttpFullRequest request, ExecutionAttributes executionAttributes) {
Aws4PresignerParams signingParams =
extractPresignerParams(Aws4PresignerParams.builder(), executionAttributes).build();
return presign(request, signingParams);
}
/**
* A method to pre sign the given #request. The parameters required for pre signing are provided through the modeled
* {@link Aws4PresignerParams} class.
*
* @param request The request to pre-sign
* @param signingParams Class with the parameters used for pre signing the request
* @return A pre signed version of the input request
*/
public SdkHttpFullRequest presign(SdkHttpFullRequest request, Aws4PresignerParams signingParams) {
// anonymous credentials, don't sign
if (CredentialUtils.isAnonymous(signingParams.awsCredentials())) {
return request;
}
signingParams = signingParams.copy(b -> b.normalizePath(false));
Aws4SignerRequestParams requestParams = new Aws4SignerRequestParams(signingParams);
return doPresign(request, requestParams, signingParams).build();
}
/**
* If necessary, creates a chunk-encoding wrapper on the request payload.
*/
@Override
protected void processRequestPayload(SdkHttpFullRequest.Builder mutableRequest,
byte[] signature,
byte[] signingKey,
Aws4SignerRequestParams signerRequestParams,
AwsS3V4SignerParams signerParams) {
processRequestPayload(mutableRequest, signature, signingKey,
signerRequestParams, signerParams, null);
}
/**
* Overloads processRequestPayload with sdkChecksum.
* Flexible Checksum for Payload is calculated if sdkChecksum is passed.
*/
@Override
protected void processRequestPayload(SdkHttpFullRequest.Builder mutableRequest,
byte[] signature,
byte[] signingKey,
Aws4SignerRequestParams signerRequestParams,
AwsS3V4SignerParams signerParams,
SdkChecksum sdkChecksum) {
if (useChunkEncoding(mutableRequest, signerParams)) {
if (mutableRequest.contentStreamProvider() != null) {
ContentStreamProvider streamProvider = mutableRequest.contentStreamProvider();
String headerForTrailerChecksumLocation = signerParams.checksumParams() != null
? signerParams.checksumParams().checksumHeaderName() : null;
mutableRequest.contentStreamProvider(() -> AbstractAwsS3V4Signer.this.asChunkEncodedStream(
streamProvider.newStream(),
signature,
signingKey,
signerRequestParams,
sdkChecksum,
headerForTrailerChecksumLocation)
);
}
}
}
@Override
protected String calculateContentHashPresign(SdkHttpFullRequest.Builder mutableRequest, Aws4PresignerParams signerParams) {
return UNSIGNED_PAYLOAD;
}
private AwsSignedChunkedEncodingInputStream asChunkEncodedStream(InputStream inputStream,
byte[] signature,
byte[] signingKey,
Aws4SignerRequestParams signerRequestParams,
SdkChecksum sdkChecksum,
String checksumHeaderForTrailer) {
AwsS3V4ChunkSigner chunkSigner = new AwsS3V4ChunkSigner(signingKey,
signerRequestParams.getFormattedRequestSigningDateTime(),
signerRequestParams.getScope());
return AwsSignedChunkedEncodingInputStream.builder()
.inputStream(inputStream)
.sdkChecksum(sdkChecksum)
.checksumHeaderForTrailer(checksumHeaderForTrailer)
.awsChunkSigner(chunkSigner)
.headerSignature(BinaryUtils.toHex(signature))
.awsChunkedEncodingConfig(AwsChunkedEncodingConfig.create())
.build();
}
/**
* Returns the pre-defined header value and set other necessary headers if
* the request needs to be chunk-encoded. Otherwise calls the superclass
* method which calculates the hash of the whole content for signing.
*/
@Override
protected String calculateContentHash(SdkHttpFullRequest.Builder mutableRequest, AwsS3V4SignerParams signerParams) {
return calculateContentHash(mutableRequest, signerParams, null);
}
/**
* This method overloads calculateContentHash with contentFlexibleChecksum.
* The contentFlexibleChecksum is computed at the same time while hash is calculated for Content.
*/
@Override
protected String calculateContentHash(SdkHttpFullRequest.Builder mutableRequest, AwsS3V4SignerParams signerParams,
SdkChecksum contentFlexibleChecksum) {
// x-amz-content-sha256 marked as STREAMING_UNSIGNED_PAYLOAD_TRAILER in interceptors if Flexible checksum is set.
boolean isUnsignedStreamingTrailer = mutableRequest.firstMatchingHeader("x-amz-content-sha256")
.map(STREAMING_UNSIGNED_PAYLOAD_TRAILER::equals)
.orElse(false);
if (!isUnsignedStreamingTrailer) {
// To be consistent with other service clients using sig-v4,
// we just set the header as "required", and AWS4Signer.sign() will be
// notified to pick up the header value returned by this method.
mutableRequest.putHeader(X_AMZ_CONTENT_SHA256, "required");
}
if (isPayloadSigningEnabled(mutableRequest, signerParams)) {
if (useChunkEncoding(mutableRequest, signerParams)) {
long originalContentLength = calculateRequestContentLength(mutableRequest);
mutableRequest.putHeader("x-amz-decoded-content-length", Long.toString(originalContentLength));
boolean isTrailingChecksum = false;
if (signerParams.checksumParams() != null) {
String headerForTrailerChecksumLocation =
signerParams.checksumParams().checksumHeaderName();
if (StringUtils.isNotBlank(headerForTrailerChecksumLocation) &&
!HttpChecksumUtils.isHttpChecksumPresent(
mutableRequest.build(),
ChecksumSpecs.builder().headerName(signerParams.checksumParams().checksumHeaderName()).build())) {
isTrailingChecksum = true;
mutableRequest.putHeader("x-amz-trailer", headerForTrailerChecksumLocation);
mutableRequest.appendHeader("Content-Encoding", "aws-chunked");
}
}
// Make sure "Content-Length" header is not empty so that HttpClient
// won't cache the stream again to recover Content-Length
long calculateStreamContentLength = AwsSignedChunkedEncodingInputStream
.calculateStreamContentLength(
originalContentLength, AwsS3V4ChunkSigner.getSignatureLength(),
AwsChunkedEncodingConfig.create(), isTrailingChecksum);
long checksumTrailerLength = isTrailingChecksum ? getChecksumTrailerLength(signerParams) : 0;
mutableRequest.putHeader(CONTENT_LENGTH, Long.toString(
calculateStreamContentLength + checksumTrailerLength));
return isTrailingChecksum ? CONTENT_SHA_256_WITH_CHECKSUM : CONTENT_SHA_256;
} else {
return super.calculateContentHash(mutableRequest, signerParams, contentFlexibleChecksum);
}
}
return isUnsignedStreamingTrailer ? STREAMING_UNSIGNED_PAYLOAD_TRAILER : UNSIGNED_PAYLOAD;
}
/**
* Determine whether to use aws-chunked for signing
*/
private boolean useChunkEncoding(SdkHttpFullRequest.Builder mutableRequest, AwsS3V4SignerParams signerParams) {
// Chunked encoding only makes sense to do when the payload is signed
return isPayloadSigningEnabled(mutableRequest, signerParams) && isChunkedEncodingEnabled(signerParams);
}
/**
* @return True if chunked encoding has been enabled. Otherwise false.
*/
private boolean isChunkedEncodingEnabled(AwsS3V4SignerParams signerParams) {
Boolean isChunkedEncodingEnabled = signerParams.enableChunkedEncoding();
return isChunkedEncodingEnabled != null && isChunkedEncodingEnabled;
}
/**
* @return True if payload signing is explicitly enabled.
*/
private boolean isPayloadSigningEnabled(SdkHttpFullRequest.Builder request, AwsS3V4SignerParams signerParams) {
/**
* If we aren't using https we should always sign the payload unless there is no payload
*/
if (!request.protocol().equals("https") && request.contentStreamProvider() != null) {
return true;
}
Boolean isPayloadSigningEnabled = signerParams.enablePayloadSigning();
return isPayloadSigningEnabled != null && isPayloadSigningEnabled;
}
public static long getChecksumTrailerLength(AwsS3V4SignerParams signerParams) {
return signerParams.checksumParams() == null ? 0
: AwsSignedChunkedEncodingInputStream.calculateChecksumContentLength(
signerParams.checksumParams().algorithm(),
signerParams.checksumParams().checksumHeaderName(),
AwsS3V4ChunkSigner.SIGNATURE_LENGTH);
}
}
| 1,728 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer/internal/AsyncSigV4SubscriberAdapter.java | /*
* 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.auth.signer.internal;
import java.nio.ByteBuffer;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import software.amazon.awssdk.annotations.SdkInternalApi;
/**
* AsyncSigV4SubscriberAdapter appends an empty frame at the end of original Publisher
* <dl>
* <dt><b>Backpressure:</b></dt>
* <dd>The trailing empty frame is sent only if there is demand from the downstream subscriber</dd>
* </dl>
*/
@SdkInternalApi
final class AsyncSigV4SubscriberAdapter implements Subscriber<ByteBuffer> {
private final AtomicBoolean upstreamDone = new AtomicBoolean(false);
private final AtomicLong downstreamDemand = new AtomicLong();
private final Object lock = new Object();
private volatile boolean sentTrailingFrame = false;
private Subscriber<? super ByteBuffer> delegate;
AsyncSigV4SubscriberAdapter(Subscriber<? super ByteBuffer> actual) {
this.delegate = actual;
}
@Override
public void onSubscribe(Subscription s) {
delegate.onSubscribe(new Subscription() {
@Override
public void request(long n) {
if (n <= 0) {
throw new IllegalArgumentException("n > 0 required but it was " + n);
}
downstreamDemand.getAndAdd(n);
if (upstreamDone.get()) {
sendTrailingEmptyFrame();
} else {
s.request(n);
}
}
@Override
public void cancel() {
s.cancel();
}
});
}
@Override
public void onNext(ByteBuffer byteBuffer) {
downstreamDemand.decrementAndGet();
delegate.onNext(byteBuffer);
}
@Override
public void onError(Throwable t) {
upstreamDone.compareAndSet(false, true);
delegate.onError(t);
}
@Override
public void onComplete() {
upstreamDone.compareAndSet(false, true);
if (downstreamDemand.get() > 0) {
sendTrailingEmptyFrame();
}
}
private void sendTrailingEmptyFrame() {
//when upstream complete, send a trailing empty frame
synchronized (lock) {
if (!sentTrailingFrame) {
sentTrailingFrame = true;
delegate.onNext(ByteBuffer.wrap(new byte[] {}));
delegate.onComplete();
}
}
}
}
| 1,729 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer/internal/BaseAsyncAws4Signer.java | /*
* 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.auth.signer.internal;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.annotations.SdkTestInternalApi;
import software.amazon.awssdk.auth.signer.params.Aws4SignerParams;
import software.amazon.awssdk.core.async.AsyncRequestBody;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.core.signer.AsyncRequestBodySigner;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.utils.Logger;
@SdkInternalApi
public abstract class BaseAsyncAws4Signer extends BaseAws4Signer implements AsyncRequestBodySigner {
private static final Logger LOG = Logger.loggerFor(BaseAsyncAws4Signer.class);
private static final Pattern AUTHENTICATION_HEADER_PATTERN = Pattern.compile(
SignerConstant.AWS4_SIGNING_ALGORITHM + "\\s" + "Credential=(\\S+)" + "\\s" + "SignedHeaders=(\\S+)" + "\\s"
+ "Signature=(\\S+)");
protected BaseAsyncAws4Signer() {
}
@Override
public AsyncRequestBody signAsyncRequestBody(SdkHttpFullRequest request, AsyncRequestBody asyncRequestBody,
ExecutionAttributes executionAttributes) {
Aws4SignerParams signingParams = extractSignerParams(Aws4SignerParams.builder(), executionAttributes)
.build();
Aws4SignerRequestParams requestParams = new Aws4SignerRequestParams(signingParams);
return signAsync(request, asyncRequestBody, requestParams, signingParams);
}
/**
* This method is only used in test, where clockOverride is passed in signingParams
*/
@SdkTestInternalApi
protected final AsyncRequestBody signAsync(SdkHttpFullRequest request, AsyncRequestBody asyncRequestBody,
Aws4SignerRequestParams requestParams, Aws4SignerParams signingParams) {
String headerSignature = getHeaderSignature(request);
return transformRequestProvider(headerSignature, requestParams, signingParams, asyncRequestBody);
}
/**
* Transform the original requestProvider by adding signing operator and returns a new requestProvider
*
* Can be overriden by subclasses to provide specific signing method
*/
protected abstract AsyncRequestBody transformRequestProvider(String headerSignature,
Aws4SignerRequestParams signerRequestParams,
Aws4SignerParams signerParams,
AsyncRequestBody asyncRequestBody);
/**
* Extract signature from Authentication header
*
* @param request signed request with Authentication header
* @return signature (Hex) string
*/
private String getHeaderSignature(SdkHttpFullRequest request) {
Optional<String> authHeader = request.firstMatchingHeader(SignerConstant.AUTHORIZATION);
if (authHeader.isPresent()) {
Matcher matcher = AUTHENTICATION_HEADER_PATTERN.matcher(authHeader.get());
if (matcher.matches()) {
String headerSignature = matcher.group(3);
return headerSignature;
}
}
// Without header signature, signer can not proceed. Thus throw out exception
throw SdkClientException.builder().message("Signature is missing in AUTHORIZATION header!").build();
}
}
| 1,730 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer/internal/ContentChecksum.java | /*
* 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.auth.signer.internal;
import java.util.Objects;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.core.checksums.SdkChecksum;
/**
* Encapsulates Hash in String format and FlexibleChecksum Instance for a Request Content.
*/
@SdkInternalApi
public class ContentChecksum {
private final String hash;
private final SdkChecksum contentFlexibleChecksum;
public ContentChecksum(String hash, SdkChecksum contentFlexibleChecksum) {
this.hash = hash;
this.contentFlexibleChecksum = contentFlexibleChecksum;
}
public String contentHash() {
return hash;
}
public SdkChecksum contentFlexibleChecksum() {
return contentFlexibleChecksum;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ContentChecksum that = (ContentChecksum) o;
return Objects.equals(hash, that.hash) &&
Objects.equals(contentFlexibleChecksum, that.contentFlexibleChecksum);
}
@Override
public int hashCode() {
int result = hash != null ? hash.hashCode() : 0;
result = 31 * result + (contentFlexibleChecksum != null ? contentFlexibleChecksum.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "ContentChecksum{" +
"hash='" + hash + '\'' +
", contentFlexibleChecksum=" + contentFlexibleChecksum +
'}';
}
}
| 1,731 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer/internal/SignerConstant.java | /*
* 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.auth.signer.internal;
import software.amazon.awssdk.annotations.SdkInternalApi;
@SdkInternalApi
public final class SignerConstant {
public static final String AWS4_TERMINATOR = "aws4_request";
public static final String AWS4_SIGNING_ALGORITHM = "AWS4-HMAC-SHA256";
/** Seconds in a week, which is the max expiration time Sig-v4 accepts. */
public static final long PRESIGN_URL_MAX_EXPIRATION_SECONDS = 60L * 60 * 24 * 7;
public static final String X_AMZ_CONTENT_SHA256 = "x-amz-content-sha256";
public static final String AUTHORIZATION = "Authorization";
static final String X_AMZ_SECURITY_TOKEN = "X-Amz-Security-Token";
static final String X_AMZ_CREDENTIAL = "X-Amz-Credential";
static final String X_AMZ_DATE = "X-Amz-Date";
static final String X_AMZ_EXPIRES = "X-Amz-Expires";
static final String X_AMZ_SIGNED_HEADER = "X-Amz-SignedHeaders";
static final String X_AMZ_SIGNATURE = "X-Amz-Signature";
static final String X_AMZ_ALGORITHM = "X-Amz-Algorithm";
static final String HOST = "Host";
static final String LINE_SEPARATOR = "\n";
private SignerConstant() {
}
}
| 1,732 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer/internal | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer/internal/util/HeaderTransformsHelper.java | /*
* 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.auth.signer.internal.util;
import static software.amazon.awssdk.utils.StringUtils.lowerCase;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;
import software.amazon.awssdk.annotations.SdkInternalApi;
/**
* Helper class for transforming headers required during signing of headers.
*/
@SdkInternalApi
public final class HeaderTransformsHelper {
private static final List<String> LIST_OF_HEADERS_TO_IGNORE_IN_LOWER_CASE =
Arrays.asList("connection", "x-amzn-trace-id", "user-agent", "expect");
private HeaderTransformsHelper() {
}
public static Map<String, List<String>> canonicalizeSigningHeaders(Map<String, List<String>> headers) {
Map<String, List<String>> result = new TreeMap<>();
for (Map.Entry<String, List<String>> header : headers.entrySet()) {
String lowerCaseHeader = lowerCase(header.getKey());
if (LIST_OF_HEADERS_TO_IGNORE_IN_LOWER_CASE.contains(lowerCaseHeader)) {
continue;
}
result.computeIfAbsent(lowerCaseHeader, x -> new ArrayList<>()).addAll(header.getValue());
}
return result;
}
/**
* "The Trimall function removes excess white space before and after values,
* and converts sequential spaces to a single space."
* <p>
* https://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html
* <p>
* The collapse-whitespace logic is equivalent to:
* <pre>
* value.replaceAll("\\s+", " ")
* </pre>
* but does not create a Pattern object that needs to compile the match
* string; it also prevents us from having to make a Matcher object as well.
*/
public static String trimAll(String value) {
boolean previousIsWhiteSpace = false;
StringBuilder sb = new StringBuilder(value.length());
for (int i = 0; i < value.length(); i++) {
char ch = value.charAt(i);
if (isWhiteSpace(ch)) {
if (previousIsWhiteSpace) {
continue;
}
sb.append(' ');
previousIsWhiteSpace = true;
} else {
sb.append(ch);
previousIsWhiteSpace = false;
}
}
return sb.toString().trim();
}
private static List<String> trimAll(List<String> values) {
return values.stream().map(HeaderTransformsHelper::trimAll).collect(Collectors.toList());
}
/**
* Tests a char to see if is it whitespace.
* This method considers the same characters to be white
* space as the Pattern class does when matching \s
*
* @param ch the character to be tested
* @return true if the character is white space, false otherwise.
*/
private static boolean isWhiteSpace(final char ch) {
return ch == ' ' || ch == '\t' || ch == '\n' || ch == '\u000b' || ch == '\r' || ch == '\f';
}
public static String getCanonicalizedHeaderString(Map<String, List<String>> canonicalizedHeaders) {
StringBuilder buffer = new StringBuilder();
canonicalizedHeaders.forEach((headerName, headerValues) -> {
buffer.append(headerName);
buffer.append(":");
buffer.append(String.join(",", trimAll(headerValues)));
buffer.append("\n");
});
return buffer.toString();
}
}
| 1,733 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer/internal | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer/internal/util/SignerMethodResolver.java | /*
* 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.auth.signer.internal.util;
import static software.amazon.awssdk.auth.signer.S3SignerExecutionAttribute.ENABLE_CHUNKED_ENCODING;
import static software.amazon.awssdk.auth.signer.S3SignerExecutionAttribute.ENABLE_PAYLOAD_SIGNING;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.auth.credentials.AwsCredentials;
import software.amazon.awssdk.auth.signer.Aws4UnsignedPayloadSigner;
import software.amazon.awssdk.auth.signer.AwsS3V4Signer;
import software.amazon.awssdk.auth.signer.internal.AbstractAwsS3V4Signer;
import software.amazon.awssdk.core.CredentialType;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.core.internal.signer.SigningMethod;
import software.amazon.awssdk.core.signer.NoOpSigner;
import software.amazon.awssdk.core.signer.Signer;
@SdkInternalApi
public final class SignerMethodResolver {
public static final String S3_SIGV4A_SIGNER_CLASS_PATH = "software.amazon.awssdk.authcrt.signer.internal"
+ ".DefaultAwsCrtS3V4aSigner";
private SignerMethodResolver() {
}
/**
* The signing method can be Header-Auth, streaming-signing auth or Unsigned-payload.
* For Aws4UnsignedPayloadSigner and ENABLE_PAYLOAD_SIGNING the protocol of request decides
* whether the request will be Unsigned or Signed.
*
* @param signer Signer Used.
* @param executionAttributes Execution attributes.
* @param credentials Credentials configured for client.
* @return SigningMethodUsed Enum based on various attributes.
*/
public static SigningMethod resolveSigningMethodUsed(Signer signer, ExecutionAttributes executionAttributes,
AwsCredentials credentials) {
SigningMethod signingMethod = SigningMethod.UNSIGNED_PAYLOAD;
if (signer != null && !CredentialType.TOKEN.equals(signer.credentialType())) {
if (isProtocolBasedStreamingSigningAuth(signer, executionAttributes)) {
signingMethod = SigningMethod.PROTOCOL_STREAMING_SIGNING_AUTH;
} else if (isProtocolBasedUnsigned(signer, executionAttributes)) {
signingMethod = SigningMethod.PROTOCOL_BASED_UNSIGNED;
} else if (isAnonymous(credentials) || signer instanceof NoOpSigner) {
signingMethod = SigningMethod.UNSIGNED_PAYLOAD;
} else {
signingMethod = SigningMethod.HEADER_BASED_AUTH;
}
}
return signingMethod;
}
private static boolean isProtocolBasedStreamingSigningAuth(Signer signer, ExecutionAttributes executionAttributes) {
return (executionAttributes.getOptionalAttribute(ENABLE_PAYLOAD_SIGNING).orElse(false) &&
executionAttributes.getOptionalAttribute(ENABLE_CHUNKED_ENCODING).orElse(false)) ||
supportsPayloadSigning(signer)
&& executionAttributes.getOptionalAttribute(ENABLE_CHUNKED_ENCODING).orElse(false);
}
// S3 Signers like sigv4 abd sigv4a signers signs the payload with chucked encoding.
private static boolean supportsPayloadSigning(Signer signer) {
if (signer == null) {
return false;
}
// auth-crt package is not a dependency of core package, thus we are directly checking the Canonical name.
return signer instanceof AbstractAwsS3V4Signer ||
S3_SIGV4A_SIGNER_CLASS_PATH.equals(signer.getClass().getCanonicalName());
}
private static boolean isProtocolBasedUnsigned(Signer signer, ExecutionAttributes executionAttributes) {
return signer instanceof Aws4UnsignedPayloadSigner || signer instanceof AwsS3V4Signer
|| executionAttributes.getOptionalAttribute(ENABLE_PAYLOAD_SIGNING).orElse(false);
}
public static boolean isAnonymous(AwsCredentials credentials) {
return credentials.secretAccessKey() == null && credentials.accessKeyId() == null;
}
}
| 1,734 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer/internal | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer/internal/chunkedencoding/AwsSignedChunkedEncodingInputStream.java | /*
* 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.auth.signer.internal.chunkedencoding;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.core.checksums.Algorithm;
import software.amazon.awssdk.core.checksums.SdkChecksum;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.core.internal.chunked.AwsChunkedEncodingConfig;
import software.amazon.awssdk.core.internal.io.AwsChunkedEncodingInputStream;
import software.amazon.awssdk.utils.BinaryUtils;
/**
* A wrapper of InputStream that implements chunked encoding.
* <p/>
* Each chunk will be buffered for the calculation of the chunk signature
* which is added at the head of each chunk. The request signature and the chunk signatures will
* be assumed to be hex-encoded strings.
* <p/>
* This class will use the mark() & reset() of the wrapped InputStream if they
* are supported, otherwise it will create a buffer for bytes read from
* the wrapped stream.
*/
@SdkInternalApi
public final class AwsSignedChunkedEncodingInputStream extends AwsChunkedEncodingInputStream {
private static final String CHUNK_SIGNATURE_HEADER = ";chunk-signature=";
private static final String CHECKSUM_SIGNATURE_HEADER = "x-amz-trailer-signature:";
private String previousChunkSignature;
private String headerSignature;
private final AwsChunkSigner chunkSigner;
/**
* Creates a chunked encoding input stream initialized with the originating stream, an http request seed signature
* and a signer that can sign a chunk of bytes according to a chosen algorithm. The configuration allows
* specification of the size of each chunk, as well as the buffer size. Use the same values as when
* calculating total length of the stream {@link #calculateStreamContentLength(long, int, AwsChunkedEncodingConfig)}.
*
* @param in The original InputStream.
* @param headerSignature The signature of the signed headers of the request. This will be used for
* calculating the signature of the first chunk. Observe that the format of
* this parameter should be a hex-encoded string.
* @param chunkSigner The signer for each chunk of data, implementing the {@link AwsChunkSigner} interface.
* @param config The configuration allows the user to customize chunk size and buffer size.
* See {@link AwsChunkedEncodingConfig} for default values.
*/
private AwsSignedChunkedEncodingInputStream(InputStream in, SdkChecksum sdkChecksum,
String checksumHeaderForTrailer,
String headerSignature,
AwsChunkSigner chunkSigner,
AwsChunkedEncodingConfig config) {
super(in, sdkChecksum, checksumHeaderForTrailer, config);
this.chunkSigner = chunkSigner;
this.previousChunkSignature = headerSignature;
this.headerSignature = headerSignature;
}
public static Builder builder() {
return new Builder();
}
public static final class Builder extends AwsChunkedEncodingInputStream.Builder<Builder> {
private AwsChunkSigner awsChunkSigner;
private String headerSignature;
/**
* @param headerSignature The signature of the signed headers. This will be used for
* calculating the signature of the first chunk
* @return This builder for method chaining.
*/
public Builder headerSignature(String headerSignature) {
this.headerSignature = headerSignature;
return this;
}
/**
*
* @param awsChunkSigner Chunk signer used to sign the data.
* @return This builder for method chaining.
*/
public Builder awsChunkSigner(AwsChunkSigner awsChunkSigner) {
this.awsChunkSigner = awsChunkSigner;
return this;
}
public AwsSignedChunkedEncodingInputStream build() {
return new AwsSignedChunkedEncodingInputStream(this.inputStream, this.sdkChecksum, this.checksumHeaderForTrailer,
this.headerSignature,
this.awsChunkSigner, this.awsChunkedEncodingConfig);
}
}
public static long calculateStreamContentLength(long originalLength,
int signatureLength,
AwsChunkedEncodingConfig config) {
return calculateStreamContentLength(originalLength, signatureLength, config, false);
}
/**
* Calculates the expected total length of signed payload chunked stream.
*
* @param originalLength The length of the data
* @param signatureLength The length of a calculated signature, dependent on which {@link AwsChunkSigner} is used
* @param config The chunked encoding config determines the size of the chunks. Use the same values as when
* initializing the stream.
*/
public static long calculateStreamContentLength(long originalLength,
int signatureLength,
AwsChunkedEncodingConfig config,
boolean isTrailingChecksumCalculated) {
if (originalLength < 0) {
throw new IllegalArgumentException("Nonnegative content length expected.");
}
int chunkSize = config.chunkSize();
long maxSizeChunks = originalLength / chunkSize;
long remainingBytes = originalLength % chunkSize;
return maxSizeChunks * calculateSignedChunkLength(chunkSize, signatureLength, false)
+ (remainingBytes > 0 ? calculateSignedChunkLength(remainingBytes, signatureLength, false) : 0)
+ calculateSignedChunkLength(0, signatureLength, isTrailingChecksumCalculated);
}
private static long calculateSignedChunkLength(long chunkDataSize, int signatureLength, boolean isTrailingCarriageReturn) {
return Long.toHexString(chunkDataSize).length()
+ CHUNK_SIGNATURE_HEADER.length()
+ signatureLength
+ CRLF.length()
+ chunkDataSize
+ (isTrailingCarriageReturn ? 0 : CRLF.length());
//For Trailing checksum we do not want additional CRLF as the checksum is appended after CRLF.
}
private byte[] createSignedChunk(byte[] chunkData) {
try {
byte[] header = createSignedChunkHeader(chunkData);
byte[] trailer = isTrailingTerminated ? CRLF.getBytes(StandardCharsets.UTF_8)
: "".getBytes(StandardCharsets.UTF_8);
byte[] signedChunk = new byte[header.length + chunkData.length + trailer.length];
System.arraycopy(header, 0, signedChunk, 0, header.length);
System.arraycopy(chunkData, 0, signedChunk, header.length, chunkData.length);
System.arraycopy(trailer, 0,
signedChunk, header.length + chunkData.length,
trailer.length);
return signedChunk;
} catch (Exception e) {
throw SdkClientException.builder()
.message("Unable to sign the chunked data. " + e.getMessage())
.cause(e)
.build();
}
}
private byte[] createSignedChunkHeader(byte[] chunkData) {
String chunkSignature = chunkSigner.signChunk(chunkData, previousChunkSignature);
previousChunkSignature = chunkSignature;
StringBuilder chunkHeader = new StringBuilder();
chunkHeader.append(Integer.toHexString(chunkData.length));
chunkHeader.append(CHUNK_SIGNATURE_HEADER)
.append(chunkSignature)
.append(CRLF);
return chunkHeader.toString().getBytes(StandardCharsets.UTF_8);
}
@Override
protected byte[] createFinalChunk(byte[] finalChunk) {
return createChunk(FINAL_CHUNK);
}
@Override
protected byte[] createChunk(byte[] chunkData) {
return createSignedChunk(chunkData);
}
@Override
protected byte[] createChecksumChunkHeader() {
StringBuilder chunkHeader = new StringBuilder();
chunkHeader.append(checksumHeaderForTrailer)
.append(HEADER_COLON_SEPARATOR)
.append(BinaryUtils.toBase64(calculatedChecksum))
.append(CRLF)
.append(createSignedChecksumChunk());
return chunkHeader.toString().getBytes(StandardCharsets.UTF_8);
}
private String createSignedChecksumChunk() {
StringBuilder chunkHeader = new StringBuilder();
//signChecksumChunk
String chunkSignature =
chunkSigner.signChecksumChunk(calculatedChecksum, previousChunkSignature,
checksumHeaderForTrailer);
previousChunkSignature = chunkSignature;
chunkHeader.append(CHECKSUM_SIGNATURE_HEADER)
.append(chunkSignature)
.append(CRLF);
return chunkHeader.toString();
}
public static int calculateChecksumContentLength(Algorithm algorithm, String headerName, int signatureLength) {
int originalLength = algorithm.base64EncodedLength();
return (headerName.length()
+ HEADER_COLON_SEPARATOR.length()
+ originalLength
+ CRLF.length()
+ calculateSignedChecksumChunkLength(signatureLength)
+ CRLF.length());
}
private static int calculateSignedChecksumChunkLength(int signatureLength) {
return CHECKSUM_SIGNATURE_HEADER.length()
+ signatureLength
+ CRLF.length();
}
@Override
public void reset() throws IOException {
super.reset();
previousChunkSignature = headerSignature;
}
}
| 1,735 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer/internal | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer/internal/chunkedencoding/AwsS3V4ChunkSigner.java | /*
* 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.auth.signer.internal.chunkedencoding;
import static software.amazon.awssdk.auth.signer.internal.util.HeaderTransformsHelper.canonicalizeSigningHeaders;
import static software.amazon.awssdk.auth.signer.internal.util.HeaderTransformsHelper.getCanonicalizedHeaderString;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.auth.signer.internal.AbstractAws4Signer;
import software.amazon.awssdk.auth.signer.internal.SigningAlgorithm;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.utils.BinaryUtils;
/**
* An implementation of AwsChunkSigner that can calculate a Sigv4 compatible chunk
* signature.
*/
@SdkInternalApi
public class AwsS3V4ChunkSigner implements AwsChunkSigner {
public static final int SIGNATURE_LENGTH = 64;
private static final String CHUNK_STRING_TO_SIGN_PREFIX = "AWS4-HMAC-SHA256-PAYLOAD";
private static final String TRAILING_HEADER_STRING_TO_SIGN_PREFIX = "AWS4-HMAC-SHA256-TRAILER";
private final String dateTime;
private final String keyPath;
private final MessageDigest sha256;
private final MessageDigest sha256ForTrailer;
private final Mac hmacSha256;
private final Mac trailerHmacSha256;
public AwsS3V4ChunkSigner(byte[] signingKey, String datetime, String keyPath) {
try {
this.sha256 = MessageDigest.getInstance("SHA-256");
this.sha256ForTrailer = MessageDigest.getInstance("SHA-256");
String signingAlgo = SigningAlgorithm.HmacSHA256.toString();
this.hmacSha256 = Mac.getInstance(signingAlgo);
hmacSha256.init(new SecretKeySpec(signingKey, signingAlgo));
trailerHmacSha256 = Mac.getInstance(signingAlgo);
trailerHmacSha256.init(new SecretKeySpec(signingKey, signingAlgo));
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException(e);
} catch (InvalidKeyException e) {
throw new IllegalArgumentException(e);
}
this.dateTime = datetime;
this.keyPath = keyPath;
}
@Override
public String signChunk(byte[] chunkData, String previousSignature) {
String chunkStringToSign =
CHUNK_STRING_TO_SIGN_PREFIX + "\n" +
dateTime + "\n" +
keyPath + "\n" +
previousSignature + "\n" +
AbstractAws4Signer.EMPTY_STRING_SHA256_HEX + "\n" +
BinaryUtils.toHex(sha256.digest(chunkData));
try {
byte[] bytes = hmacSha256.doFinal(chunkStringToSign.getBytes(StandardCharsets.UTF_8));
return BinaryUtils.toHex(bytes);
} catch (Exception e) {
throw SdkClientException.builder()
.message("Unable to calculate a request signature: " + e.getMessage())
.cause(e)
.build();
}
}
/**
* Signed chunk must be of below format
* signature = Hex(HMAC(K,
* "AWS4-HMAC-SHA256-TRAILER"\n
* DATE\n
* KEYPATH\n
* final_chunk_signature\n
* Hex(SHA256(canonicalize(trailing-headers)))))
* @return Signed Checksum in above signature format.
*/
public String signChecksumChunk(byte[] calculatedChecksum, String previousSignature, String checksumHeaderForTrailer) {
Map<String, List<String>> canonicalizeSigningHeaders = canonicalizeSigningHeaders(
Collections.singletonMap(checksumHeaderForTrailer, Arrays.asList(BinaryUtils.toBase64(calculatedChecksum))));
String canonicalizedHeaderString = getCanonicalizedHeaderString(canonicalizeSigningHeaders);
String chunkStringToSign =
TRAILING_HEADER_STRING_TO_SIGN_PREFIX + "\n" +
dateTime + "\n" +
keyPath + "\n" +
previousSignature + "\n" +
BinaryUtils.toHex(sha256ForTrailer.digest(canonicalizedHeaderString.getBytes(StandardCharsets.UTF_8)));
return BinaryUtils.toHex(trailerHmacSha256.doFinal(chunkStringToSign.getBytes(StandardCharsets.UTF_8)));
}
public static int getSignatureLength() {
return SIGNATURE_LENGTH;
}
}
| 1,736 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer/internal | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer/internal/chunkedencoding/AwsChunkSigner.java | /*
* 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.auth.signer.internal.chunkedencoding;
import software.amazon.awssdk.annotations.SdkInternalApi;
/**
* Represents a signer for a chunk of data, that returns a new signature based on the data and the
* previous signature. This signature should be a string of hex characters.
*/
@SdkInternalApi
public interface AwsChunkSigner {
String signChunk(byte[] chunkData, String previousSignature);
String signChecksumChunk(byte[] calculatedChecksum, String previousSignature, String checksumHeaderForTrailer);
}
| 1,737 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer/params/Aws4PresignerParams.java | /*
* 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.auth.signer.params;
import java.time.Instant;
import java.util.Optional;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.auth.signer.internal.SignerConstant;
import software.amazon.awssdk.utils.builder.CopyableBuilder;
import software.amazon.awssdk.utils.builder.ToCopyableBuilder;
@SdkPublicApi
public final class Aws4PresignerParams
extends Aws4SignerParams
implements ToCopyableBuilder<Aws4PresignerParams.Builder, Aws4PresignerParams> {
private final Instant expirationTime;
private Aws4PresignerParams(BuilderImpl builder) {
super(builder);
this.expirationTime = builder.expirationTime;
}
public Optional<Instant> expirationTime() {
return Optional.ofNullable(expirationTime);
}
public static Builder builder() {
return new BuilderImpl();
}
@Override
public Builder toBuilder() {
return new BuilderImpl(this);
}
public interface Builder extends Aws4SignerParams.Builder<Builder>, CopyableBuilder<Builder, Aws4PresignerParams> {
/**
* Sets an expiration time for the presigned url. If this value is not specified,
* {@link SignerConstant#PRESIGN_URL_MAX_EXPIRATION_SECONDS} is used.
*
* @param expirationTime Expiration time for the presigned url expressed in {@link Instant}.
*/
Builder expirationTime(Instant expirationTime);
@Override
Aws4PresignerParams build();
}
private static final class BuilderImpl extends Aws4SignerParams.BuilderImpl<Builder> implements Builder {
private Instant expirationTime;
private BuilderImpl() {
}
private BuilderImpl(Aws4PresignerParams params) {
super(params);
this.expirationTime = params.expirationTime;
}
@Override
public Builder expirationTime(Instant expirationTime) {
this.expirationTime = expirationTime;
return this;
}
public void setExpirationTime(Instant expirationTime) {
expirationTime(expirationTime);
}
@Override
public Aws4PresignerParams build() {
return new Aws4PresignerParams(this);
}
}
}
| 1,738 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer/params/AwsS3V4SignerParams.java | /*
* 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.auth.signer.params;
import software.amazon.awssdk.annotations.SdkPublicApi;
@SdkPublicApi
public final class AwsS3V4SignerParams extends Aws4SignerParams {
private final Boolean enableChunkedEncoding;
private final Boolean enablePayloadSigning;
private AwsS3V4SignerParams(BuilderImpl builder) {
super(builder);
this.enableChunkedEncoding = builder.enableChunkedEncoding;
this.enablePayloadSigning = builder.enablePayloadSigning;
}
public Boolean enableChunkedEncoding() {
return enableChunkedEncoding;
}
public Boolean enablePayloadSigning() {
return enablePayloadSigning;
}
public static Builder builder() {
return new BuilderImpl();
}
public interface Builder extends Aws4SignerParams.Builder<Builder> {
/**
* <p>
* Configures the client to enable chunked encoding for all requests.
* </p>
* <p>
* The default behavior is to enable chunked encoding automatically. Disable this flag will result in
* disabling chunked encoding for all requests.
* </p>
* <p>
* <b>Note:</b> Disabling this option has performance implications since the checksum for the
* payload will have to be pre-calculated before sending the data. If your payload is large this
* will affect the overall time required to upload an object. Using this option is recommended
* only if your endpoint does not implement chunked uploading.
* </p>
*
* @param enableChunkedEncoding True to enable chunked encoding and False to disable. Default value is True.
*/
Builder enableChunkedEncoding(Boolean enableChunkedEncoding);
/**
* <p>
* Configures the client to sign payloads in all situations.
* </p>
* <p>
* Payload signing is optional when chunked encoding is not used and requests are made
* against an HTTPS endpoint. Under these conditions the client will by default
* opt to not sign payloads to optimize performance. If this flag is set to true the
* client will instead always sign payloads.
* </p>
* <p>
* <b>Note:</b> Payload signing can be expensive, particularly if transferring
* large payloads in a single chunk. Enabling this option will result in a performance
* penalty.
* </p>
*
* @param enablePayloadSigning True to explicitly enable payload signing in all situations. Default value is False.
*/
Builder enablePayloadSigning(Boolean enablePayloadSigning);
@Override
AwsS3V4SignerParams build();
}
private static final class BuilderImpl extends Aws4SignerParams.BuilderImpl<Builder> implements Builder {
static final boolean DEFAULT_CHUNKED_ENCODING_ENABLED = false;
static final boolean DEFAULT_PAYLOAD_SIGNING_ENABLED = false;
private Boolean enableChunkedEncoding = DEFAULT_CHUNKED_ENCODING_ENABLED;
private Boolean enablePayloadSigning = DEFAULT_PAYLOAD_SIGNING_ENABLED;
private BuilderImpl() {
// By default, S3 should not normalize paths
normalizePath(false);
}
@Override
public Builder enableChunkedEncoding(Boolean enableChunkedEncoding) {
this.enableChunkedEncoding = enableChunkedEncoding;
return this;
}
public void setEnableChunkedEncoding(Boolean enableChunkedEncoding) {
enableChunkedEncoding(enableChunkedEncoding);
}
@Override
public Builder enablePayloadSigning(Boolean enablePayloadSigning) {
this.enablePayloadSigning = enablePayloadSigning;
return this;
}
public void setEnablePayloadSigning(Boolean enablePayloadSigning) {
enablePayloadSigning(enablePayloadSigning);
}
@Override
public AwsS3V4SignerParams build() {
return new AwsS3V4SignerParams(this);
}
}
}
| 1,739 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer/params/SignerChecksumParams.java | /*
* 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.auth.signer.params;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.core.checksums.Algorithm;
import software.amazon.awssdk.utils.Validate;
/**
* Encapsulates the Checksum information like Algorithm and header name for the checksum in header/trailer locations.
*/
@SdkPublicApi
public class SignerChecksumParams {
private final Algorithm algorithm;
private final String checksumHeaderName;
private final boolean isStreamingRequest;
private SignerChecksumParams(Builder builder) {
Validate.notNull(builder.algorithm, "algorithm is null");
Validate.notNull(builder.checksumHeaderName, "checksumHeaderName is null");
this.algorithm = builder.algorithm;
this.checksumHeaderName = builder.checksumHeaderName;
this.isStreamingRequest = builder.isStreamingRequest;
}
public static Builder builder() {
return new Builder();
}
/**
* @return {@code Algorithm} that will be used to compute the checksum.
*/
public Algorithm algorithm() {
return algorithm;
}
/**
*
* @return Header name for the checksum.
*/
public String checksumHeaderName() {
return checksumHeaderName;
}
/**
*
* @return true if the checksum is for a streaming request member.
*/
public boolean isStreamingRequest() {
return isStreamingRequest;
}
public static final class Builder {
private Algorithm algorithm;
private String checksumHeaderName;
private boolean isStreamingRequest;
private Builder() {
}
/**
* @param algorithm {@code Algorithm} that will be used to compute checksum for the content.
* @return this builder for method chaining.
*/
public Builder algorithm(Algorithm algorithm) {
this.algorithm = algorithm;
return this;
}
/**
*
* @param checksumHeaderName Header name for the Checksum.
* @return this builder for method chaining.
*/
public Builder checksumHeaderName(String checksumHeaderName) {
this.checksumHeaderName = checksumHeaderName;
return this;
}
/**
*
* @param isStreamingRequest True if the request has a streaming memberin it.
* @return this builder for method chaining.
*/
public Builder isStreamingRequest(boolean isStreamingRequest) {
this.isStreamingRequest = isStreamingRequest;
return this;
}
/**
* Builds an instance of {@link SignerChecksumParams}.
*
* @return New instance of {@link SignerChecksumParams}.
*/
public SignerChecksumParams build() {
return new SignerChecksumParams(this);
}
}
}
| 1,740 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer/params/Aws4SignerParams.java | /*
* 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.auth.signer.params;
import java.time.Clock;
import java.util.Optional;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.auth.credentials.AwsCredentials;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.utils.Validate;
/**
* Parameters that are used during signing.
*
* Required parameters vary based on signer implementations. Signer implementations might only use a
* subset of params in this class.
*/
@SdkPublicApi
public class Aws4SignerParams {
private final Boolean doubleUrlEncode;
private final Boolean normalizePath;
private final AwsCredentials awsCredentials;
private final String signingName;
private final Region signingRegion;
private final Integer timeOffset;
private final Clock signingClockOverride;
private final SignerChecksumParams checksumParams;
Aws4SignerParams(BuilderImpl<?> builder) {
this.doubleUrlEncode = Validate.paramNotNull(builder.doubleUrlEncode, "Double url encode");
this.normalizePath = Validate.paramNotNull(builder.normalizePath, "Normalize resource path");
this.awsCredentials = Validate.paramNotNull(builder.awsCredentials, "Credentials");
this.signingName = Validate.paramNotNull(builder.signingName, "service signing name");
this.signingRegion = Validate.paramNotNull(builder.signingRegion, "signing region");
this.timeOffset = builder.timeOffset;
this.signingClockOverride = builder.signingClockOverride;
this.checksumParams = builder.checksumParams;
}
public static Builder builder() {
return new BuilderImpl<>();
}
public Boolean doubleUrlEncode() {
return doubleUrlEncode;
}
public Boolean normalizePath() {
return normalizePath;
}
public AwsCredentials awsCredentials() {
return awsCredentials;
}
public String signingName() {
return signingName;
}
public Region signingRegion() {
return signingRegion;
}
public Optional<Integer> timeOffset() {
return Optional.ofNullable(timeOffset);
}
public Optional<Clock> signingClockOverride() {
return Optional.ofNullable(signingClockOverride);
}
public SignerChecksumParams checksumParams() {
return checksumParams;
}
public interface Builder<B extends Builder<B>> {
/**
* Set this value to double url-encode the resource path when constructing the
* canonical request.
*
* By default, all services except S3 enable double url-encoding.
*
* @param doubleUrlEncode Set true to enable double url encoding. Otherwise false.
*/
B doubleUrlEncode(Boolean doubleUrlEncode);
/**
* Whether the resource path should be "normalized" according to RFC3986 when
* constructing the canonical request.
*
* By default, all services except S3 enable resource path normalization.
*/
B normalizePath(Boolean normalizePath);
/**
* Sets the aws credentials to use for computing the signature.
*
* @param awsCredentials Aws Credentials to use for computing the signature.
*/
B awsCredentials(AwsCredentials awsCredentials);
/**
* The name of the AWS service to be used for computing the signature.
*
* @param signingName Name of the AWS service to be used for computing the signature.
*/
B signingName(String signingName);
/**
* The AWS region to be used for computing the signature.
*
* @param signingRegion AWS region to be used for computing the signature.
*/
B signingRegion(Region signingRegion);
/**
* The time offset (for clock skew correction) to use when computing the signing date for the request.
*
* @param timeOffset The time offset (for clock skew correction) to use when computing the signing date for the request.
*/
B timeOffset(Integer timeOffset);
/**
* The clock to use for overriding the signing time when computing signature for a request.
*
* By default, current time of the system is used for signing. This parameter can be used to set custom signing time.
* Useful option for testing.
*
* @param signingClockOverride The clock to use for overriding the signing time when computing signature for a request.
*/
B signingClockOverride(Clock signingClockOverride);
/**
* Checksum params required to compute the Checksum while data is read for signing the Checksum.
*
* @param checksumParams SignerChecksumParams that defines the Algorithm and headers to pass Checksum.
* @return
*/
B checksumParams(SignerChecksumParams checksumParams);
Aws4SignerParams build();
}
protected static class BuilderImpl<B extends Builder<B>> implements Builder<B> {
private static final Boolean DEFAULT_DOUBLE_URL_ENCODE = Boolean.TRUE;
private Boolean doubleUrlEncode = DEFAULT_DOUBLE_URL_ENCODE;
private Boolean normalizePath = Boolean.TRUE;
private AwsCredentials awsCredentials;
private String signingName;
private Region signingRegion;
private Integer timeOffset;
private Clock signingClockOverride;
private SignerChecksumParams checksumParams;
protected BuilderImpl() {
}
protected BuilderImpl(Aws4SignerParams params) {
doubleUrlEncode = params.doubleUrlEncode;
normalizePath = params.normalizePath;
awsCredentials = params.awsCredentials;
signingName = params.signingName;
signingRegion = params.signingRegion;
timeOffset = params.timeOffset;
signingClockOverride = params.signingClockOverride;
checksumParams = params.checksumParams;
}
@Override
public B doubleUrlEncode(Boolean doubleUrlEncode) {
this.doubleUrlEncode = doubleUrlEncode;
return (B) this;
}
public void setDoubleUrlEncode(Boolean doubleUrlEncode) {
doubleUrlEncode(doubleUrlEncode);
}
@Override
public B normalizePath(Boolean normalizePath) {
this.normalizePath = normalizePath;
return (B) this;
}
public void setNormalizePath(Boolean normalizePath) {
normalizePath(normalizePath);
}
@Override
public B awsCredentials(AwsCredentials awsCredentials) {
this.awsCredentials = awsCredentials;
return (B) this;
}
public void setAwsCredentials(AwsCredentials awsCredentials) {
awsCredentials(awsCredentials);
}
@Override
public B signingName(String signingName) {
this.signingName = signingName;
return (B) this;
}
public void setSigningName(String signingName) {
signingName(signingName);
}
@Override
public B signingRegion(Region signingRegion) {
this.signingRegion = signingRegion;
return (B) this;
}
public void setSigningRegion(Region signingRegion) {
signingRegion(signingRegion);
}
@Override
public B timeOffset(Integer timeOffset) {
this.timeOffset = timeOffset;
return (B) this;
}
public void setTimeOffset(Integer timeOffset) {
timeOffset(timeOffset);
}
@Override
public B signingClockOverride(Clock signingClockOverride) {
this.signingClockOverride = signingClockOverride;
return (B) this;
}
@Override
public B checksumParams(SignerChecksumParams checksumParams) {
this.checksumParams = checksumParams;
return (B) this;
}
public void setSigningClockOverride(Clock signingClockOverride) {
signingClockOverride(signingClockOverride);
}
@Override
public Aws4SignerParams build() {
return new Aws4SignerParams(this);
}
}
}
| 1,741 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/signer/params/TokenSignerParams.java | /*
* 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.auth.signer.params;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.auth.token.credentials.SdkToken;
import software.amazon.awssdk.utils.Validate;
/**
* Parameters that are used during signing.
*
* Required parameters vary based on signer implementations. Signer implementations might only use a
* subset of params in this class.
*/
@SdkPublicApi
public class TokenSignerParams {
private final SdkToken token;
TokenSignerParams(BuilderImpl<?> builder) {
this.token = Validate.paramNotNull(builder.token, "Signing token");
}
public static Builder builder() {
return new BuilderImpl<>();
}
public SdkToken token() {
return token;
}
public interface Builder<B extends Builder> {
/**
* Set this value to provide a token for signing
*
* This is required for token signing.
*
* @param token A token implementing {@link SdkToken}
*/
B token(SdkToken token);
TokenSignerParams build();
}
protected static class BuilderImpl<B extends Builder> implements Builder<B> {
private SdkToken token;
protected BuilderImpl() {
}
@Override
public B token(SdkToken token) {
this.token = token;
return (B) this;
}
public void setToken(SdkToken token) {
token(token);
}
@Override
public TokenSignerParams build() {
return new TokenSignerParams(this);
}
}
}
| 1,742 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/credentials/DefaultCredentialsProvider.java | /*
* 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.auth.credentials;
import java.util.Optional;
import java.util.function.Supplier;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.auth.credentials.internal.LazyAwsCredentialsProvider;
import software.amazon.awssdk.profiles.ProfileFile;
import software.amazon.awssdk.profiles.ProfileFileSupplier;
import software.amazon.awssdk.utils.SdkAutoCloseable;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.builder.CopyableBuilder;
import software.amazon.awssdk.utils.builder.ToCopyableBuilder;
/**
* AWS credentials provider chain that looks for credentials in this order:
* <ol>
* <li>Java System Properties - {@code aws.accessKeyId} and {@code aws.secretAccessKey}</li>
* <li>Environment Variables - {@code AWS_ACCESS_KEY_ID} and {@code AWS_SECRET_ACCESS_KEY}</li>
* <li>Web Identity Token credentials from system properties or environment variables</li>
* <li>Credential profiles file at the default location (~/.aws/credentials) shared by all AWS SDKs and the AWS CLI</li>
* <li>Credentials delivered through the Amazon EC2 container service if AWS_CONTAINER_CREDENTIALS_RELATIVE_URI" environment
* variable is set and security manager has permission to access the variable,</li>
* <li>Instance profile credentials delivered through the Amazon EC2 metadata service</li>
* </ol>
*
* @see SystemPropertyCredentialsProvider
* @see EnvironmentVariableCredentialsProvider
* @see ProfileCredentialsProvider
* @see WebIdentityTokenFileCredentialsProvider
* @see ContainerCredentialsProvider
* @see InstanceProfileCredentialsProvider
*/
@SdkPublicApi
public final class DefaultCredentialsProvider
implements AwsCredentialsProvider, SdkAutoCloseable,
ToCopyableBuilder<DefaultCredentialsProvider.Builder, DefaultCredentialsProvider> {
private static final DefaultCredentialsProvider DEFAULT_CREDENTIALS_PROVIDER = new DefaultCredentialsProvider(builder());
private final LazyAwsCredentialsProvider providerChain;
private final Supplier<ProfileFile> profileFile;
private final String profileName;
private final Boolean reuseLastProviderEnabled;
private final Boolean asyncCredentialUpdateEnabled;
/**
* @see #builder()
*/
private DefaultCredentialsProvider(Builder builder) {
this.profileFile = builder.profileFile;
this.profileName = builder.profileName;
this.reuseLastProviderEnabled = builder.reuseLastProviderEnabled;
this.asyncCredentialUpdateEnabled = builder.asyncCredentialUpdateEnabled;
this.providerChain = createChain(builder);
}
/**
* Create an instance of the {@link DefaultCredentialsProvider} using the default configuration. Configuration can be
* specified by creating an instance using the {@link #builder()}.
*/
public static DefaultCredentialsProvider create() {
return DEFAULT_CREDENTIALS_PROVIDER;
}
/**
* Create the default credential chain using the configuration in the provided builder.
*/
private static LazyAwsCredentialsProvider createChain(Builder builder) {
boolean asyncCredentialUpdateEnabled = builder.asyncCredentialUpdateEnabled;
boolean reuseLastProviderEnabled = builder.reuseLastProviderEnabled;
return LazyAwsCredentialsProvider.create(() -> {
AwsCredentialsProvider[] credentialsProviders = new AwsCredentialsProvider[] {
SystemPropertyCredentialsProvider.create(),
EnvironmentVariableCredentialsProvider.create(),
WebIdentityTokenFileCredentialsProvider.builder()
.asyncCredentialUpdateEnabled(asyncCredentialUpdateEnabled)
.build(),
ProfileCredentialsProvider.builder()
.profileFile(builder.profileFile)
.profileName(builder.profileName)
.build(),
ContainerCredentialsProvider.builder()
.asyncCredentialUpdateEnabled(asyncCredentialUpdateEnabled)
.build(),
InstanceProfileCredentialsProvider.builder()
.asyncCredentialUpdateEnabled(asyncCredentialUpdateEnabled)
.profileFile(builder.profileFile)
.profileName(builder.profileName)
.build()
};
return AwsCredentialsProviderChain.builder()
.reuseLastProviderEnabled(reuseLastProviderEnabled)
.credentialsProviders(credentialsProviders)
.build();
});
}
/**
* Get a builder for defining a {@link DefaultCredentialsProvider} with custom configuration.
*/
public static Builder builder() {
return new Builder();
}
@Override
public AwsCredentials resolveCredentials() {
return providerChain.resolveCredentials();
}
@Override
public void close() {
providerChain.close();
}
@Override
public String toString() {
return ToString.builder("DefaultCredentialsProvider")
.add("providerChain", providerChain)
.build();
}
@Override
public Builder toBuilder() {
return new Builder(this);
}
/**
* Configuration that defines the {@link DefaultCredentialsProvider}'s behavior.
*/
public static final class Builder implements CopyableBuilder<Builder, DefaultCredentialsProvider> {
private Supplier<ProfileFile> profileFile;
private String profileName;
private Boolean reuseLastProviderEnabled = true;
private Boolean asyncCredentialUpdateEnabled = false;
/**
* Created with {@link #builder()}.
*/
private Builder() {
}
private Builder(DefaultCredentialsProvider credentialsProvider) {
this.profileFile = credentialsProvider.profileFile;
this.profileName = credentialsProvider.profileName;
this.reuseLastProviderEnabled = credentialsProvider.reuseLastProviderEnabled;
this.asyncCredentialUpdateEnabled = credentialsProvider.asyncCredentialUpdateEnabled;
}
public Builder profileFile(ProfileFile profileFile) {
return profileFile(Optional.ofNullable(profileFile)
.map(ProfileFileSupplier::fixedProfileFile)
.orElse(null));
}
public Builder profileFile(Supplier<ProfileFile> profileFileSupplier) {
this.profileFile = profileFileSupplier;
return this;
}
public Builder profileName(String profileName) {
this.profileName = profileName;
return this;
}
/**
* Controls whether the provider should reuse the last successful credentials provider in the chain. Reusing the last
* successful credentials provider will typically return credentials faster than searching through the chain.
*
* <p>By default, this is enabled.</p>
*/
public Builder reuseLastProviderEnabled(Boolean reuseLastProviderEnabled) {
this.reuseLastProviderEnabled = reuseLastProviderEnabled;
return this;
}
/**
* Configure whether this provider should fetch credentials asynchronously in the background. If this is true, threads are
* less likely to block when {@link #resolveCredentials()} is called, but additional resources are used to maintain the
* provider.
*
* <p>By default, this is disabled.</p>
*/
public Builder asyncCredentialUpdateEnabled(Boolean asyncCredentialUpdateEnabled) {
this.asyncCredentialUpdateEnabled = asyncCredentialUpdateEnabled;
return this;
}
/**
* Create a {@link DefaultCredentialsProvider} using the configuration defined in this builder.
*/
@Override
public DefaultCredentialsProvider build() {
return new DefaultCredentialsProvider(this);
}
}
}
| 1,743 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/credentials/ProfileCredentialsProviderFactory.java | /*
* 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.auth.credentials;
import software.amazon.awssdk.annotations.SdkProtectedApi;
/**
* A factory for {@link AwsCredentialsProvider}s, which can be used to create different credentials providers with different
* Provider specifications like profile properties.
*/
@FunctionalInterface
@SdkProtectedApi
public interface ProfileCredentialsProviderFactory {
AwsCredentialsProvider create(ProfileProviderCredentialsContext profileProviderCredentialsContext);
}
| 1,744 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/credentials/AwsCredentialsProvider.java | /*
* 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.auth.credentials;
import java.util.concurrent.CompletableFuture;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity;
import software.amazon.awssdk.identity.spi.IdentityProvider;
import software.amazon.awssdk.identity.spi.ResolveIdentityRequest;
/**
* Interface for loading {@link AwsCredentials} that are used for authentication.
*
* <p>Commonly-used implementations include {@link StaticCredentialsProvider} for a fixed set of credentials and the
* {@link DefaultCredentialsProvider} for discovering credentials from the host's environment. The AWS Security Token
* Service (STS) client also provides implementations of this interface for loading temporary, limited-privilege credentials from
* AWS STS.</p>
*/
@FunctionalInterface
@SdkPublicApi
public interface AwsCredentialsProvider extends IdentityProvider<AwsCredentialsIdentity> {
/**
* Returns {@link AwsCredentials} that can be used to authorize an AWS request. Each implementation of AWSCredentialsProvider
* can choose its own strategy for loading credentials. For example, an implementation might load credentials from an existing
* key management system, or load new credentials when credentials are rotated.
*
* <p>If an error occurs during the loading of credentials or credentials could not be found, a runtime exception will be
* raised.</p>
*
* @return AwsCredentials which the caller can use to authorize an AWS request.
*/
AwsCredentials resolveCredentials();
@Override
default Class<AwsCredentialsIdentity> identityType() {
return AwsCredentialsIdentity.class;
}
@Override
default CompletableFuture<AwsCredentialsIdentity> resolveIdentity(ResolveIdentityRequest request) {
return CompletableFuture.completedFuture(resolveCredentials());
}
}
| 1,745 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/credentials/ProcessCredentialsProvider.java | /*
* 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.auth.credentials;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.protocols.jsoncore.JsonNode;
import software.amazon.awssdk.protocols.jsoncore.JsonNodeParser;
import software.amazon.awssdk.utils.DateUtils;
import software.amazon.awssdk.utils.IoUtils;
import software.amazon.awssdk.utils.Platform;
import software.amazon.awssdk.utils.SdkAutoCloseable;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.Validate;
import software.amazon.awssdk.utils.builder.CopyableBuilder;
import software.amazon.awssdk.utils.builder.ToCopyableBuilder;
import software.amazon.awssdk.utils.cache.CachedSupplier;
import software.amazon.awssdk.utils.cache.NonBlocking;
import software.amazon.awssdk.utils.cache.RefreshResult;
/**
* A credentials provider that can load credentials from an external process. This is used to support the credential_process
* setting in the profile credentials file. See
* <a href="https://docs.aws.amazon.com/cli/latest/topic/config-vars.html#sourcing-credentials-from-external-processes">sourcing credentials
* from external processes</a> for more information.
*
* <p>
* This class can be initialized using {@link #builder()}.
*
* <p>
* Available settings:
* <ul>
* <li>Command - The command that should be executed to retrieve credentials.</li>
* <li>CredentialRefreshThreshold - The amount of time between when the credentials expire and when the credentials should
* start to be refreshed. This allows the credentials to be refreshed *before* they are reported to expire. Default: 15
* seconds.</li>
* <li>ProcessOutputLimit - The maximum amount of data that can be returned by the external process before an exception is
* raised. Default: 64000 bytes (64KB).</li>
* </ul>
*/
@SdkPublicApi
public final class ProcessCredentialsProvider
implements AwsCredentialsProvider,
SdkAutoCloseable,
ToCopyableBuilder<ProcessCredentialsProvider.Builder, ProcessCredentialsProvider> {
private static final JsonNodeParser PARSER = JsonNodeParser.builder()
.removeErrorLocations(true)
.build();
private final List<String> executableCommand;
private final Duration credentialRefreshThreshold;
private final long processOutputLimit;
private final CachedSupplier<AwsCredentials> processCredentialCache;
private final String commandFromBuilder;
private final Boolean asyncCredentialUpdateEnabled;
/**
* @see #builder()
*/
private ProcessCredentialsProvider(Builder builder) {
List<String> cmd = new ArrayList<>();
if (Platform.isWindows()) {
cmd.add("cmd.exe");
cmd.add("/C");
} else {
cmd.add("sh");
cmd.add("-c");
}
String builderCommand = Validate.paramNotNull(builder.command, "command");
cmd.add(builderCommand);
this.executableCommand = Collections.unmodifiableList(cmd);
this.processOutputLimit = Validate.isPositive(builder.processOutputLimit, "processOutputLimit");
this.credentialRefreshThreshold = Validate.isPositive(builder.credentialRefreshThreshold, "expirationBuffer");
this.commandFromBuilder = builder.command;
this.asyncCredentialUpdateEnabled = builder.asyncCredentialUpdateEnabled;
CachedSupplier.Builder<AwsCredentials> cacheBuilder = CachedSupplier.builder(this::refreshCredentials)
.cachedValueName(toString());
if (builder.asyncCredentialUpdateEnabled) {
cacheBuilder.prefetchStrategy(new NonBlocking("process-credentials-provider"));
}
this.processCredentialCache = cacheBuilder.build();
}
/**
* Retrieve a new builder that can be used to create and configure a {@link ProcessCredentialsProvider}.
*/
public static Builder builder() {
return new Builder();
}
@Override
public AwsCredentials resolveCredentials() {
return processCredentialCache.get();
}
private RefreshResult<AwsCredentials> refreshCredentials() {
try {
String processOutput = executeCommand();
JsonNode credentialsJson = parseProcessOutput(processOutput);
AwsCredentials credentials = credentials(credentialsJson);
Instant credentialExpirationTime = credentialExpirationTime(credentialsJson);
return RefreshResult.builder(credentials)
.staleTime(credentialExpirationTime)
.prefetchTime(credentialExpirationTime.minusMillis(credentialRefreshThreshold.toMillis()))
.build();
} catch (InterruptedException e) {
throw new IllegalStateException("Process-based credential refreshing has been interrupted.", e);
} catch (Exception e) {
throw new IllegalStateException("Failed to refresh process-based credentials.", e);
}
}
/**
* Parse the output from the credentials process.
*/
private JsonNode parseProcessOutput(String processOutput) {
JsonNode credentialsJson = PARSER.parse(processOutput);
if (!credentialsJson.isObject()) {
throw new IllegalStateException("Process did not return a JSON object.");
}
JsonNode version = credentialsJson.field("Version").orElse(null);
if (version == null || !version.isNumber() || !version.asNumber().equals("1")) {
throw new IllegalStateException("Unsupported credential version: " + version);
}
return credentialsJson;
}
/**
* Parse the process output to retrieve the credentials.
*/
private AwsCredentials credentials(JsonNode credentialsJson) {
String accessKeyId = getText(credentialsJson, "AccessKeyId");
String secretAccessKey = getText(credentialsJson, "SecretAccessKey");
String sessionToken = getText(credentialsJson, "SessionToken");
Validate.notEmpty(accessKeyId, "AccessKeyId cannot be empty.");
Validate.notEmpty(secretAccessKey, "SecretAccessKey cannot be empty.");
if (sessionToken != null) {
return AwsSessionCredentials.create(accessKeyId, secretAccessKey, sessionToken);
} else {
return AwsBasicCredentials.create(accessKeyId, secretAccessKey);
}
}
/**
* Parse the process output to retrieve the expiration date and time.
*/
private Instant credentialExpirationTime(JsonNode credentialsJson) {
String expiration = getText(credentialsJson, "Expiration");
if (expiration != null) {
return DateUtils.parseIso8601Date(expiration);
} else {
return Instant.MAX;
}
}
/**
* Get a textual value from a json object.
*/
private String getText(JsonNode jsonObject, String nodeName) {
return jsonObject.field(nodeName).map(JsonNode::text).orElse(null);
}
/**
* Execute the external process to retrieve credentials.
*/
private String executeCommand() throws IOException, InterruptedException {
ProcessBuilder processBuilder = new ProcessBuilder(executableCommand);
ByteArrayOutputStream commandOutput = new ByteArrayOutputStream();
Process process = processBuilder.start();
try {
IoUtils.copy(process.getInputStream(), commandOutput, processOutputLimit);
process.waitFor();
if (process.exitValue() != 0) {
try (InputStream errorStream = process.getErrorStream()) {
String errorMessage = IoUtils.toUtf8String(errorStream);
throw new IllegalStateException(String.format("Command returned non-zero exit value (%s) with error message: "
+ "%s", process.exitValue(), errorMessage));
}
}
return new String(commandOutput.toByteArray(), StandardCharsets.UTF_8);
} finally {
process.destroy();
}
}
@Override
public void close() {
processCredentialCache.close();
}
@Override
public Builder toBuilder() {
return new Builder(this);
}
/**
* Used to configure and create a {@link ProcessCredentialsProvider}. See {@link #builder()} creation.
*/
public static class Builder implements CopyableBuilder<Builder, ProcessCredentialsProvider> {
private Boolean asyncCredentialUpdateEnabled = false;
private String command;
private Duration credentialRefreshThreshold = Duration.ofSeconds(15);
private long processOutputLimit = 64000;
/**
* @see #builder()
*/
private Builder() {
}
private Builder(ProcessCredentialsProvider provider) {
this.asyncCredentialUpdateEnabled = provider.asyncCredentialUpdateEnabled;
this.command = provider.commandFromBuilder;
this.credentialRefreshThreshold = provider.credentialRefreshThreshold;
this.processOutputLimit = provider.processOutputLimit;
}
/**
* Configure whether the provider should fetch credentials asynchronously in the background. If this is true,
* threads are less likely to block when credentials are loaded, but additional resources are used to maintain
* the provider.
*
* <p>By default, this is disabled.</p>
*/
@SuppressWarnings("unchecked")
public Builder asyncCredentialUpdateEnabled(Boolean asyncCredentialUpdateEnabled) {
this.asyncCredentialUpdateEnabled = asyncCredentialUpdateEnabled;
return this;
}
/**
* Configure the command that should be executed to retrieve credentials.
*/
public Builder command(String command) {
this.command = command;
return this;
}
/**
* Configure the amount of time between when the credentials expire and when the credentials should start to be
* refreshed. This allows the credentials to be refreshed *before* they are reported to expire.
*
* <p>Default: 15 seconds.</p>
*/
public Builder credentialRefreshThreshold(Duration credentialRefreshThreshold) {
this.credentialRefreshThreshold = credentialRefreshThreshold;
return this;
}
/**
* Configure the maximum amount of data that can be returned by the external process before an exception is
* raised.
*
* <p>Default: 64000 bytes (64KB).</p>
*/
public Builder processOutputLimit(long outputByteLimit) {
this.processOutputLimit = outputByteLimit;
return this;
}
public ProcessCredentialsProvider build() {
return new ProcessCredentialsProvider(this);
}
}
@Override
public String toString() {
return ToString.builder("ProcessCredentialsProvider")
.add("cmd", executableCommand)
.build();
}
} | 1,746 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/credentials/WebIdentityTokenCredentialsProviderFactory.java | /*
* 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.auth.credentials;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.auth.credentials.internal.WebIdentityTokenCredentialProperties;
import software.amazon.awssdk.profiles.Profile;
/**
* A factory for {@link AwsCredentialsProvider}s that are derived from web identity tokens.
*
* Currently this is used to allow a {@link Profile} or environment variable configured with a role that should be assumed with
* a web identity token to create a credentials provider via the
* 'software.amazon.awssdk.services.sts.internal.StsWebIdentityCredentialsProviderFactory', assuming STS is on the classpath.
*/
@FunctionalInterface
@SdkProtectedApi
public interface WebIdentityTokenCredentialsProviderFactory {
AwsCredentialsProvider create(WebIdentityTokenCredentialProperties credentialProperties);
}
| 1,747 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/credentials/StaticCredentialsProvider.java | /*
* 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.auth.credentials;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.Validate;
/**
* An implementation of {@link AwsCredentialsProvider} that returns a set implementation of {@link AwsCredentials}.
*/
@SdkPublicApi
public final class StaticCredentialsProvider implements AwsCredentialsProvider {
private final AwsCredentials credentials;
private StaticCredentialsProvider(AwsCredentials credentials) {
this.credentials = Validate.notNull(credentials, "Credentials must not be null.");
}
/**
* Create a credentials provider that always returns the provided set of credentials.
*/
public static StaticCredentialsProvider create(AwsCredentials credentials) {
return new StaticCredentialsProvider(credentials);
}
@Override
public AwsCredentials resolveCredentials() {
return credentials;
}
@Override
public String toString() {
return ToString.builder("StaticCredentialsProvider")
.add("credentials", credentials)
.build();
}
}
| 1,748 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/credentials/AwsBasicCredentials.java | /*
* 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.auth.credentials;
import static software.amazon.awssdk.utils.StringUtils.trimToNull;
import java.util.Objects;
import software.amazon.awssdk.annotations.Immutable;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.Validate;
/**
* Provides access to the AWS credentials used for accessing services: AWS access key ID and secret access key. These
* credentials are used to securely sign requests to services (e.g., AWS services) that use them for authentication.
*
* <p>For more details on AWS access keys, see:
* <a href="https://docs.aws.amazon.com/general/latest/gr/aws-sec-cred-types.html#access-keys-and-secret-access-keys">
* https://docs.aws.amazon.com/general/latest/gr/aws-sec-cred-types.html#access-keys-and-secret-access-keys</a></p>
*
* @see AwsCredentialsProvider
*/
@Immutable
@SdkPublicApi
public final class AwsBasicCredentials implements AwsCredentials {
/**
* A set of AWS credentials without an access key or secret access key, indicating that anonymous access should be used.
*
* This should be accessed via {@link AnonymousCredentialsProvider#resolveCredentials()}.
*/
@SdkInternalApi
static final AwsBasicCredentials ANONYMOUS_CREDENTIALS = new AwsBasicCredentials(null, null, false);
private final String accessKeyId;
private final String secretAccessKey;
/**
* Constructs a new credentials object, with the specified AWS access key and AWS secret key.
*
* @param accessKeyId The AWS access key, used to identify the user interacting with AWS.
* @param secretAccessKey The AWS secret access key, used to authenticate the user interacting with AWS.
*/
protected AwsBasicCredentials(String accessKeyId, String secretAccessKey) {
this(accessKeyId, secretAccessKey, true);
}
private AwsBasicCredentials(String accessKeyId, String secretAccessKey, boolean validateCredentials) {
this.accessKeyId = trimToNull(accessKeyId);
this.secretAccessKey = trimToNull(secretAccessKey);
if (validateCredentials) {
Validate.notNull(this.accessKeyId, "Access key ID cannot be blank.");
Validate.notNull(this.secretAccessKey, "Secret access key cannot be blank.");
}
}
/**
* Constructs a new credentials object, with the specified AWS access key and AWS secret key.
*
* @param accessKeyId The AWS access key, used to identify the user interacting with AWS.
* @param secretAccessKey The AWS secret access key, used to authenticate the user interacting with AWS.
* */
public static AwsBasicCredentials create(String accessKeyId, String secretAccessKey) {
return new AwsBasicCredentials(accessKeyId, secretAccessKey);
}
/**
* Retrieve the AWS access key, used to identify the user interacting with AWS.
*/
@Override
public String accessKeyId() {
return accessKeyId;
}
/**
* Retrieve the AWS secret access key, used to authenticate the user interacting with AWS.
*/
@Override
public String secretAccessKey() {
return secretAccessKey;
}
@Override
public String toString() {
return ToString.builder("AwsCredentials")
.add("accessKeyId", accessKeyId)
.build();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
AwsBasicCredentials that = (AwsBasicCredentials) o;
return Objects.equals(accessKeyId, that.accessKeyId) &&
Objects.equals(secretAccessKey, that.secretAccessKey);
}
@Override
public int hashCode() {
int hashCode = 1;
hashCode = 31 * hashCode + Objects.hashCode(accessKeyId());
hashCode = 31 * hashCode + Objects.hashCode(secretAccessKey());
return hashCode;
}
}
| 1,749 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/credentials/HttpCredentialsProvider.java | /*
* 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.auth.credentials;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.utils.SdkAutoCloseable;
/**
* A base for many credential providers within the SDK that rely on calling a remote HTTP endpoint to refresh credentials.
*
* @see InstanceProfileCredentialsProvider
* @see ContainerCredentialsProvider
*/
@SdkPublicApi
public interface HttpCredentialsProvider extends AwsCredentialsProvider, SdkAutoCloseable {
interface Builder<TypeToBuildT extends HttpCredentialsProvider, BuilderT extends Builder<?, ?>> {
/**
* Configure whether the provider should fetch credentials asynchronously in the background. If this is true,
* threads are less likely to block when credentials are loaded, but additional resources are used to maintain
* the provider.
*
* <p>By default, this is disabled.</p>
*/
BuilderT asyncCredentialUpdateEnabled(Boolean asyncCredentialUpdateEnabled);
/**
* When {@link #asyncCredentialUpdateEnabled(Boolean)} is true, this configures the name of the threads used for
* credential refreshing.
*/
BuilderT asyncThreadName(String asyncThreadName);
/**
* Override the default hostname (not path) that is used for credential refreshing. Most users do not need to modify
* this behavior, except for testing purposes where mocking the HTTP credential source would be useful.
*/
BuilderT endpoint(String endpoint);
/**
* Build the credentials provider based on the configuration on this builder.
*/
TypeToBuildT build();
}
}
| 1,750 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/credentials/EnvironmentVariableCredentialsProvider.java | /*
* 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.auth.credentials;
import java.util.Optional;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.auth.credentials.internal.SystemSettingsCredentialsProvider;
import software.amazon.awssdk.utils.SystemSetting;
import software.amazon.awssdk.utils.ToString;
/**
* {@link AwsCredentialsProvider} implementation that loads credentials from the AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY and
* AWS_SESSION_TOKEN environment variables.
*/
@SdkPublicApi
public final class EnvironmentVariableCredentialsProvider extends SystemSettingsCredentialsProvider {
private EnvironmentVariableCredentialsProvider() {
}
public static EnvironmentVariableCredentialsProvider create() {
return new EnvironmentVariableCredentialsProvider();
}
@Override
protected Optional<String> loadSetting(SystemSetting setting) {
// CHECKSTYLE:OFF - Customers should be able to specify a credentials provider that only looks at the environment
// variables, but not the system properties. For that reason, we're only checking the environment variable here.
return SystemSetting.getStringValueFromEnvironmentVariable(setting.environmentVariable());
// CHECKSTYLE:ON
}
@Override
public String toString() {
return ToString.create("EnvironmentVariableCredentialsProvider");
}
}
| 1,751 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/credentials/WebIdentityTokenFileCredentialsProvider.java | /*
* 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.auth.credentials;
import static software.amazon.awssdk.utils.StringUtils.trim;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Duration;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.auth.credentials.internal.WebIdentityCredentialsUtils;
import software.amazon.awssdk.auth.credentials.internal.WebIdentityTokenCredentialProperties;
import software.amazon.awssdk.core.SdkSystemSetting;
import software.amazon.awssdk.utils.IoUtils;
import software.amazon.awssdk.utils.Logger;
import software.amazon.awssdk.utils.SdkAutoCloseable;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.builder.CopyableBuilder;
import software.amazon.awssdk.utils.builder.ToCopyableBuilder;
/**
* A credential provider that will read web identity token file path, aws role arn and aws session name from system properties or
* environment variables for using web identity token credentials with STS.
* <p>
* Use of this credentials provider requires the 'sts' module to be on the classpath.
* </p>
* <p>
* StsWebIdentityTokenFileCredentialsProvider in sts package can be used instead of this class if any one of following is
* required
* <ul>
* <li>Pass a custom StsClient to the provider. </li>
* <li>Periodically update credentials </li>
* </ul>
*
* @see AwsCredentialsProvider
*/
@SdkPublicApi
public class WebIdentityTokenFileCredentialsProvider
implements AwsCredentialsProvider, SdkAutoCloseable,
ToCopyableBuilder<WebIdentityTokenFileCredentialsProvider.Builder, WebIdentityTokenFileCredentialsProvider> {
private static final Logger log = Logger.loggerFor(WebIdentityTokenFileCredentialsProvider.class);
private final AwsCredentialsProvider credentialsProvider;
private final RuntimeException loadException;
private final String roleArn;
private final String roleSessionName;
private final Path webIdentityTokenFile;
private final Boolean asyncCredentialUpdateEnabled;
private final Duration prefetchTime;
private final Duration staleTime;
private final Duration roleSessionDuration;
private WebIdentityTokenFileCredentialsProvider(BuilderImpl builder) {
AwsCredentialsProvider credentialsProvider = null;
RuntimeException loadException = null;
String roleArn = null;
String roleSessionName = null;
Path webIdentityTokenFile = null;
Boolean asyncCredentialUpdateEnabled = null;
Duration prefetchTime = null;
Duration staleTime = null;
Duration roleSessionDuration = null;
try {
webIdentityTokenFile =
builder.webIdentityTokenFile != null ? builder.webIdentityTokenFile
: Paths.get(trim(SdkSystemSetting.AWS_WEB_IDENTITY_TOKEN_FILE
.getStringValueOrThrow()));
roleArn = builder.roleArn != null ? builder.roleArn
: trim(SdkSystemSetting.AWS_ROLE_ARN.getStringValueOrThrow());
roleSessionName =
builder.roleSessionName != null ? builder.roleSessionName
: SdkSystemSetting.AWS_ROLE_SESSION_NAME.getStringValue().orElse(null);
asyncCredentialUpdateEnabled =
builder.asyncCredentialUpdateEnabled != null ? builder.asyncCredentialUpdateEnabled : false;
prefetchTime = builder.prefetchTime;
staleTime = builder.staleTime;
roleSessionDuration = builder.roleSessionDuration;
WebIdentityTokenCredentialProperties credentialProperties =
WebIdentityTokenCredentialProperties.builder()
.roleArn(roleArn)
.roleSessionName(roleSessionName)
.webIdentityTokenFile(webIdentityTokenFile)
.asyncCredentialUpdateEnabled(asyncCredentialUpdateEnabled)
.prefetchTime(prefetchTime)
.staleTime(staleTime)
.roleSessionDuration(roleSessionDuration)
.build();
credentialsProvider = WebIdentityCredentialsUtils.factory().create(credentialProperties);
} catch (RuntimeException e) {
// If we couldn't load the credentials provider for some reason, save an exception describing why. This exception
// will only be raised on calls to getCredentials. We don't want to raise an exception here because it may be
// expected (eg. in the default credential chain).
loadException = e;
}
this.loadException = loadException;
this.credentialsProvider = credentialsProvider;
this.roleArn = roleArn;
this.roleSessionName = roleSessionName;
this.webIdentityTokenFile = webIdentityTokenFile;
this.asyncCredentialUpdateEnabled = asyncCredentialUpdateEnabled;
this.prefetchTime = prefetchTime;
this.staleTime = staleTime;
this.roleSessionDuration = roleSessionDuration;
}
public static WebIdentityTokenFileCredentialsProvider create() {
return WebIdentityTokenFileCredentialsProvider.builder().build();
}
@Override
public AwsCredentials resolveCredentials() {
if (loadException != null) {
throw loadException;
}
return credentialsProvider.resolveCredentials();
}
public static Builder builder() {
return new BuilderImpl();
}
@Override
public String toString() {
return ToString.create("WebIdentityTokenCredentialsProvider");
}
@Override
public Builder toBuilder() {
return new BuilderImpl(this);
}
@Override
public void close() {
IoUtils.closeIfCloseable(credentialsProvider, null);
}
/**
* A builder for creating a custom {@link WebIdentityTokenFileCredentialsProvider}.
*/
public interface Builder extends CopyableBuilder<Builder, WebIdentityTokenFileCredentialsProvider> {
/**
* Define the role arn that should be used by this credentials provider.
*/
Builder roleArn(String roleArn);
/**
* Define the role session name that should be used by this credentials provider.
*/
Builder roleSessionName(String roleSessionName);
/**
* Define the absolute path to the web identity token file that should be used by this credentials provider.
*/
Builder webIdentityTokenFile(Path webIdentityTokenFile);
/**
* Define whether the provider should fetch credentials asynchronously in the background.
*/
Builder asyncCredentialUpdateEnabled(Boolean asyncCredentialUpdateEnabled);
/**
* Configure the amount of time, relative to STS token expiration, that the cached credentials are considered close to
* stale and should be updated.
*
* <p>Prefetch updates will occur between the specified time and the stale time of the provider. Prefetch
* updates may be asynchronous. See {@link #asyncCredentialUpdateEnabled}.
*
* <p>By default, this is 5 minutes.
*/
Builder prefetchTime(Duration prefetchTime);
/**
* Configure the amount of time, relative to STS token expiration, that the cached credentials are considered stale and
* must be updated. All threads will block until the value is updated.
*
* <p>By default, this is 1 minute.
*/
Builder staleTime(Duration staleTime);
/**
* @param sessionDuration
* @return
*/
Builder roleSessionDuration(Duration sessionDuration);
/**
* Create a {@link WebIdentityTokenFileCredentialsProvider} using the configuration applied to this builder.
*/
WebIdentityTokenFileCredentialsProvider build();
}
static final class BuilderImpl implements Builder {
private String roleArn;
private String roleSessionName;
private Path webIdentityTokenFile;
private Boolean asyncCredentialUpdateEnabled;
private Duration prefetchTime;
private Duration staleTime;
private Duration roleSessionDuration;
BuilderImpl() {
}
private BuilderImpl(WebIdentityTokenFileCredentialsProvider provider) {
this.roleArn = provider.roleArn;
this.roleSessionName = provider.roleSessionName;
this.webIdentityTokenFile = provider.webIdentityTokenFile;
this.asyncCredentialUpdateEnabled = provider.asyncCredentialUpdateEnabled;
this.prefetchTime = provider.prefetchTime;
this.staleTime = provider.staleTime;
this.roleSessionDuration = provider.roleSessionDuration;
}
@Override
public Builder roleArn(String roleArn) {
this.roleArn = roleArn;
return this;
}
public void setRoleArn(String roleArn) {
roleArn(roleArn);
}
@Override
public Builder roleSessionName(String roleSessionName) {
this.roleSessionName = roleSessionName;
return this;
}
public void setRoleSessionName(String roleSessionName) {
roleSessionName(roleSessionName);
}
@Override
public Builder webIdentityTokenFile(Path webIdentityTokenFile) {
this.webIdentityTokenFile = webIdentityTokenFile;
return this;
}
public void setWebIdentityTokenFile(Path webIdentityTokenFile) {
webIdentityTokenFile(webIdentityTokenFile);
}
@Override
public Builder asyncCredentialUpdateEnabled(Boolean asyncCredentialUpdateEnabled) {
this.asyncCredentialUpdateEnabled = asyncCredentialUpdateEnabled;
return this;
}
public void setAsyncCredentialUpdateEnabled(Boolean asyncCredentialUpdateEnabled) {
asyncCredentialUpdateEnabled(asyncCredentialUpdateEnabled);
}
@Override
public Builder prefetchTime(Duration prefetchTime) {
this.prefetchTime = prefetchTime;
return this;
}
public void setPrefetchTime(Duration prefetchTime) {
prefetchTime(prefetchTime);
}
@Override
public Builder staleTime(Duration staleTime) {
this.staleTime = staleTime;
return this;
}
public void setStaleTime(Duration staleTime) {
staleTime(staleTime);
}
@Override
public Builder roleSessionDuration(Duration sessionDuration) {
this.roleSessionDuration = sessionDuration;
return this;
}
public void setRoleSessionDuration(Duration roleSessionDuration) {
roleSessionDuration(roleSessionDuration);
}
@Override
public WebIdentityTokenFileCredentialsProvider build() {
return new WebIdentityTokenFileCredentialsProvider(this);
}
}
}
| 1,752 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/credentials/ProfileCredentialsProvider.java | /*
* 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.auth.credentials;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.function.Supplier;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.annotations.SdkTestInternalApi;
import software.amazon.awssdk.auth.credentials.internal.ProfileCredentialsUtils;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.profiles.ProfileFile;
import software.amazon.awssdk.profiles.ProfileFileSupplier;
import software.amazon.awssdk.profiles.ProfileFileSystemSetting;
import software.amazon.awssdk.utils.IoUtils;
import software.amazon.awssdk.utils.SdkAutoCloseable;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.builder.CopyableBuilder;
import software.amazon.awssdk.utils.builder.ToCopyableBuilder;
/**
* Credentials provider based on AWS configuration profiles. This loads credentials from a {@link ProfileFile}, allowing you to
* share multiple sets of AWS security credentials between different tools like the AWS SDK for Java and the AWS CLI.
*
* <p>See http://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html</p>
*
* <p>If this credentials provider is loading assume-role credentials from STS, it should be cleaned up with {@link #close()} if
* it is no longer being used.</p>
*
* @see ProfileFile
*/
@SdkPublicApi
public final class ProfileCredentialsProvider
implements AwsCredentialsProvider,
SdkAutoCloseable,
ToCopyableBuilder<ProfileCredentialsProvider.Builder, ProfileCredentialsProvider> {
private volatile AwsCredentialsProvider credentialsProvider;
private final RuntimeException loadException;
private final Supplier<ProfileFile> profileFile;
private volatile ProfileFile currentProfileFile;
private final String profileName;
private final Supplier<ProfileFile> defaultProfileFileLoader;
private final Object credentialsProviderLock = new Object();
/**
* @see #builder()
*/
private ProfileCredentialsProvider(BuilderImpl builder) {
this.defaultProfileFileLoader = builder.defaultProfileFileLoader;
RuntimeException thrownException = null;
String selectedProfileName = null;
Supplier<ProfileFile> selectedProfileSupplier = null;
try {
selectedProfileName = Optional.ofNullable(builder.profileName)
.orElseGet(ProfileFileSystemSetting.AWS_PROFILE::getStringValueOrThrow);
selectedProfileSupplier = Optional.ofNullable(builder.profileFile)
.orElseGet(() -> builder.defaultProfileFileLoader);
} catch (RuntimeException e) {
// If we couldn't load the credentials provider for some reason, save an exception describing why. This exception
// will only be raised on calls to resolveCredentials. We don't want to raise an exception here because it may be
// expected (eg. in the default credential chain).
thrownException = e;
}
this.loadException = thrownException;
this.profileName = selectedProfileName;
this.profileFile = selectedProfileSupplier;
}
/**
* Create a {@link ProfileCredentialsProvider} using the {@link ProfileFile#defaultProfileFile()} and default profile name.
* Use {@link #builder()} for defining a custom {@link ProfileCredentialsProvider}.
*/
public static ProfileCredentialsProvider create() {
return builder().build();
}
/**
* Create a {@link ProfileCredentialsProvider} using the given profile name and {@link ProfileFile#defaultProfileFile()}. Use
* {@link #builder()} for defining a custom {@link ProfileCredentialsProvider}.
*
* @param profileName the name of the profile to use from the {@link ProfileFile#defaultProfileFile()}
*/
public static ProfileCredentialsProvider create(String profileName) {
return builder().profileName(profileName).build();
}
/**
* Get a builder for creating a custom {@link ProfileCredentialsProvider}.
*/
public static Builder builder() {
return new BuilderImpl();
}
@Override
public AwsCredentials resolveCredentials() {
if (loadException != null) {
throw loadException;
}
ProfileFile cachedOrRefreshedProfileFile = refreshProfileFile();
if (shouldUpdateCredentialsProvider(cachedOrRefreshedProfileFile)) {
synchronized (credentialsProviderLock) {
if (shouldUpdateCredentialsProvider(cachedOrRefreshedProfileFile)) {
currentProfileFile = cachedOrRefreshedProfileFile;
handleProfileFileReload(cachedOrRefreshedProfileFile);
}
}
}
return credentialsProvider.resolveCredentials();
}
private void handleProfileFileReload(ProfileFile profileFile) {
credentialsProvider = createCredentialsProvider(profileFile, profileName);
}
private ProfileFile refreshProfileFile() {
return profileFile.get();
}
private boolean shouldUpdateCredentialsProvider(ProfileFile profileFile) {
return credentialsProvider == null || !Objects.equals(currentProfileFile, profileFile);
}
@Override
public String toString() {
return ToString.builder("ProfileCredentialsProvider")
.add("profileName", profileName)
.add("profileFile", currentProfileFile)
.build();
}
@Override
public void close() {
// The delegate credentials provider may be closeable (eg. if it's an STS credentials provider). In this case, we should
// clean it up when this credentials provider is closed.
IoUtils.closeIfCloseable(credentialsProvider, null);
}
@Override
public Builder toBuilder() {
return new BuilderImpl(this);
}
private AwsCredentialsProvider createCredentialsProvider(ProfileFile profileFile, String profileName) {
// Load the profile and credentials provider
return profileFile.profile(profileName)
.flatMap(p -> new ProfileCredentialsUtils(profileFile, p, profileFile::profile).credentialsProvider())
.orElseThrow(() -> {
String errorMessage = String.format("Profile file contained no credentials for " +
"profile '%s': %s", profileName, profileFile);
return SdkClientException.builder().message(errorMessage).build();
});
}
/**
* A builder for creating a custom {@link ProfileCredentialsProvider}.
*/
public interface Builder extends CopyableBuilder<Builder, ProfileCredentialsProvider> {
/**
* Define the profile file that should be used by this credentials provider. By default, the
* {@link ProfileFile#defaultProfileFile()} is used.
* @see #profileFile(Supplier)
*/
Builder profileFile(ProfileFile profileFile);
/**
* Similar to {@link #profileFile(ProfileFile)}, but takes a lambda to configure a new {@link ProfileFile.Builder}. This
* removes the need to called {@link ProfileFile#builder()} and {@link ProfileFile.Builder#build()}.
*/
Builder profileFile(Consumer<ProfileFile.Builder> profileFile);
/**
* Define the mechanism for loading profile files.
*
* @param profileFileSupplier Supplier interface for generating a ProfileFile instance.
* @see #profileFile(ProfileFile)
*/
Builder profileFile(Supplier<ProfileFile> profileFileSupplier);
/**
* Define the name of the profile that should be used by this credentials provider. By default, the value in
* {@link ProfileFileSystemSetting#AWS_PROFILE} is used.
*/
Builder profileName(String profileName);
/**
* Create a {@link ProfileCredentialsProvider} using the configuration applied to this builder.
*/
@Override
ProfileCredentialsProvider build();
}
static final class BuilderImpl implements Builder {
private Supplier<ProfileFile> profileFile;
private String profileName;
private Supplier<ProfileFile> defaultProfileFileLoader = ProfileFile::defaultProfileFile;
BuilderImpl() {
}
BuilderImpl(ProfileCredentialsProvider provider) {
this.profileName = provider.profileName;
this.defaultProfileFileLoader = provider.defaultProfileFileLoader;
this.profileFile = provider.profileFile;
}
@Override
public Builder profileFile(ProfileFile profileFile) {
return profileFile(Optional.ofNullable(profileFile)
.map(ProfileFileSupplier::fixedProfileFile)
.orElse(null));
}
public void setProfileFile(ProfileFile profileFile) {
profileFile(profileFile);
}
@Override
public Builder profileFile(Consumer<ProfileFile.Builder> profileFile) {
return profileFile(ProfileFile.builder().applyMutation(profileFile).build());
}
@Override
public Builder profileFile(Supplier<ProfileFile> profileFileSupplier) {
this.profileFile = profileFileSupplier;
return this;
}
public void setProfileFile(Supplier<ProfileFile> supplier) {
profileFile(supplier);
}
@Override
public Builder profileName(String profileName) {
this.profileName = profileName;
return this;
}
public void setProfileName(String profileName) {
profileName(profileName);
}
@Override
public ProfileCredentialsProvider build() {
return new ProfileCredentialsProvider(this);
}
/**
* Override the default configuration file to be used when the customer does not explicitly set
* profileFile(ProfileFile) or profileFileSupplier(supplier);
* {@link #profileFile(ProfileFile)}. Use of this method is
* only useful for testing the default behavior.
*/
@SdkTestInternalApi
Builder defaultProfileFileLoader(Supplier<ProfileFile> defaultProfileFileLoader) {
this.defaultProfileFileLoader = defaultProfileFileLoader;
return this;
}
}
}
| 1,753 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/credentials/CredentialUtils.java | /*
* 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.auth.credentials;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity;
import software.amazon.awssdk.identity.spi.AwsSessionCredentialsIdentity;
import software.amazon.awssdk.identity.spi.IdentityProvider;
import software.amazon.awssdk.utils.CompletableFutureUtils;
@SdkProtectedApi
public final class CredentialUtils {
private CredentialUtils() {
}
/**
* Determine whether the provided credentials are anonymous credentials, indicating that the customer is not attempting to
* authenticate themselves.
*/
public static boolean isAnonymous(AwsCredentials credentials) {
return isAnonymous((AwsCredentialsIdentity) credentials);
}
/**
* Determine whether the provided credentials are anonymous credentials, indicating that the customer is not attempting to
* authenticate themselves.
*/
public static boolean isAnonymous(AwsCredentialsIdentity credentials) {
return credentials.secretAccessKey() == null && credentials.accessKeyId() == null;
}
/**
* Converts an {@link AwsCredentialsIdentity} to {@link AwsCredentials}.
*
* <p>Usage of the new AwsCredentialsIdentity type is preferred over AwsCredentials. But some places may need to still
* convert to the older AwsCredentials type to work with existing code.</p>
*
* <p>The conversion is only aware of {@link AwsCredentialsIdentity} and {@link AwsSessionCredentialsIdentity} types. If the
* input is another sub-type that has other properties, they are not carried over. i.e.,
* <ul>
* <li>AwsSessionCredentialsIdentity -> AwsSessionCredentials</li>
* <li>AwsCredentialsIdentity -> AwsBasicCredentials</li>
* </ul>
* </p>
*
* @param awsCredentialsIdentity The {@link AwsCredentialsIdentity} to convert
* @return The corresponding {@link AwsCredentials}
*/
public static AwsCredentials toCredentials(AwsCredentialsIdentity awsCredentialsIdentity) {
if (awsCredentialsIdentity == null) {
return null;
}
if (awsCredentialsIdentity instanceof AwsCredentials) {
return (AwsCredentials) awsCredentialsIdentity;
}
// identity-spi defines 2 known types - AwsCredentialsIdentity and a sub-type AwsSessionCredentialsIdentity
if (awsCredentialsIdentity instanceof AwsSessionCredentialsIdentity) {
AwsSessionCredentialsIdentity awsSessionCredentialsIdentity = (AwsSessionCredentialsIdentity) awsCredentialsIdentity;
return AwsSessionCredentials.create(awsSessionCredentialsIdentity.accessKeyId(),
awsSessionCredentialsIdentity.secretAccessKey(),
awsSessionCredentialsIdentity.sessionToken());
}
if (isAnonymous(awsCredentialsIdentity)) {
return AwsBasicCredentials.ANONYMOUS_CREDENTIALS;
}
return AwsBasicCredentials.create(awsCredentialsIdentity.accessKeyId(),
awsCredentialsIdentity.secretAccessKey());
}
/**
* Converts an {@link IdentityProvider<? extends AwsCredentialsIdentity>} to {@link AwsCredentialsProvider} based on
* {@link #toCredentials(AwsCredentialsIdentity)}.
*
* <p>Usage of the new IdentityProvider type is preferred over AwsCredentialsProvider. But some places may need to still
* convert to the older AwsCredentialsProvider type to work with existing code.
* </p>
*
* @param identityProvider The {@link IdentityProvider<? extends AwsCredentialsIdentity>} to convert
* @return The corresponding {@link AwsCredentialsProvider}
*/
public static AwsCredentialsProvider toCredentialsProvider(
IdentityProvider<? extends AwsCredentialsIdentity> identityProvider) {
if (identityProvider == null) {
return null;
}
if (identityProvider instanceof AwsCredentialsProvider) {
return (AwsCredentialsProvider) identityProvider;
}
return () -> {
AwsCredentialsIdentity awsCredentialsIdentity =
CompletableFutureUtils.joinLikeSync(identityProvider.resolveIdentity());
return toCredentials(awsCredentialsIdentity);
};
}
}
| 1,754 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/credentials/AwsCredentials.java | /*
* 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.auth.credentials;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity;
/**
* Provides access to the AWS credentials used for accessing services: AWS access key ID and secret access key. These
* credentials are used to securely sign requests to services (e.g., AWS services) that use them for authentication.
*
* <p>For more details on AWS access keys, see:
* <a href="https://docs.aws.amazon.com/general/latest/gr/aws-sec-cred-types.html#access-keys-and-secret-access-keys">
* https://docs.aws.amazon.com/general/latest/gr/aws-sec-cred-types.html#access-keys-and-secret-access-keys</a></p>
*
* @see AwsCredentialsProvider
*/
@SdkPublicApi
public interface AwsCredentials extends AwsCredentialsIdentity {
}
| 1,755 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/credentials/ProfileProviderCredentialsContext.java | /*
* 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.auth.credentials;
import java.util.Objects;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.profiles.Profile;
import software.amazon.awssdk.profiles.ProfileFile;
/**
* Context class that defines the required properties for creation of a Credentials provider.
*/
@SdkProtectedApi
public final class ProfileProviderCredentialsContext {
private final Profile profile;
private final ProfileFile profileFile;
private ProfileProviderCredentialsContext(Profile profile, ProfileFile profileFile) {
this.profile = profile;
this.profileFile = profileFile;
}
public static Builder builder() {
return new Builder();
}
/**
* Getter method for profile.
* @return The profile that should be used to load the configuration necessary to create the credential provider.
*/
public Profile profile() {
return profile;
}
/**
* Getter for profileFile.
* @return ProfileFile that has the profile which is used to create the credential provider.
*/
public ProfileFile profileFile() {
return profileFile;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ProfileProviderCredentialsContext that = (ProfileProviderCredentialsContext) o;
return Objects.equals(profile, that.profile) && Objects.equals(profileFile, that.profileFile);
}
@Override
public int hashCode() {
int result = profile != null ? profile.hashCode() : 0;
result = 31 * result + (profileFile != null ? profileFile.hashCode() : 0);
return result;
}
public static final class Builder {
private Profile profile;
private ProfileFile profileFile;
private Builder() {
}
/**
* Builder interface to set profile.
* @param profile The profile that should be used to load the configuration necessary to create the credential provider.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Builder profile(Profile profile) {
this.profile = profile;
return this;
}
/**
* Builder interface to set ProfileFile.
* @param profileFile The ProfileFile that has the profile which is used to create the credential provider. This is *
* required to fetch the titles like sso-session defined in profile property* *
* @return Returns a reference to this object so that method calls can be chained together.
*/
public Builder profileFile(ProfileFile profileFile) {
this.profileFile = profileFile;
return this;
}
public ProfileProviderCredentialsContext build() {
return new ProfileProviderCredentialsContext(profile, profileFile);
}
}
}
| 1,756 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/credentials/AwsCredentialsProviderChain.java | /*
* 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.auth.credentials;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.identity.spi.AwsCredentialsIdentity;
import software.amazon.awssdk.identity.spi.IdentityProvider;
import software.amazon.awssdk.utils.CompletableFutureUtils;
import software.amazon.awssdk.utils.IoUtils;
import software.amazon.awssdk.utils.Logger;
import software.amazon.awssdk.utils.SdkAutoCloseable;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.Validate;
import software.amazon.awssdk.utils.builder.CopyableBuilder;
import software.amazon.awssdk.utils.builder.ToCopyableBuilder;
/**
* {@link AwsCredentialsProvider} implementation that chains together multiple credentials providers.
*
* <p>When a caller first requests credentials from this provider, it calls all the providers in the chain, in the original order
* specified, until one can provide credentials, and then returns those credentials. If all of the credential providers in the
* chain have been called, and none of them can provide credentials, then this class will throw an exception indicated that no
* credentials are available.</p>
*
* <p>By default, this class will remember the first credentials provider in the chain that was able to provide credentials, and
* will continue to use that provider when credentials are requested in the future, instead of traversing the chain each time.
* This behavior can be controlled through the {@link Builder#reuseLastProviderEnabled(Boolean)} method.</p>
*
* <p>This chain implements {@link AutoCloseable}. When closed, it will call the {@link AutoCloseable#close()} on any credential
* providers in the chain that need to be closed.</p>
*/
@SdkPublicApi
public final class AwsCredentialsProviderChain
implements AwsCredentialsProvider,
SdkAutoCloseable,
ToCopyableBuilder<AwsCredentialsProviderChain.Builder, AwsCredentialsProviderChain> {
private static final Logger log = Logger.loggerFor(AwsCredentialsProviderChain.class);
private final List<IdentityProvider<? extends AwsCredentialsIdentity>> credentialsProviders;
private final boolean reuseLastProviderEnabled;
private volatile IdentityProvider<? extends AwsCredentialsIdentity> lastUsedProvider;
/**
* @see #builder()
*/
private AwsCredentialsProviderChain(BuilderImpl builder) {
Validate.notEmpty(builder.credentialsProviders, "No credential providers were specified.");
this.reuseLastProviderEnabled = builder.reuseLastProviderEnabled;
this.credentialsProviders = Collections.unmodifiableList(builder.credentialsProviders);
}
/**
* Get a new builder for creating a {@link AwsCredentialsProviderChain}.
*/
public static Builder builder() {
return new BuilderImpl();
}
/**
* Create an AWS credentials provider chain with default configuration that checks the given credential providers.
* @param awsCredentialsProviders The credentials providers that should be checked for credentials, in the order they should
* be checked.
* @return A credential provider chain that checks the provided credential providers in order.
*/
public static AwsCredentialsProviderChain of(AwsCredentialsProvider... awsCredentialsProviders) {
return builder().credentialsProviders(awsCredentialsProviders).build();
}
/**
* Create an AWS credentials provider chain with default configuration that checks the given credential providers.
* @param awsCredentialsProviders The credentials providers that should be checked for credentials, in the order they should
* be checked.
* @return A credential provider chain that checks the provided credential providers in order.
*/
public static AwsCredentialsProviderChain of(IdentityProvider<? extends AwsCredentialsIdentity>... awsCredentialsProviders) {
return builder().credentialsProviders(awsCredentialsProviders).build();
}
@Override
public AwsCredentials resolveCredentials() {
if (reuseLastProviderEnabled && lastUsedProvider != null) {
return CredentialUtils.toCredentials(CompletableFutureUtils.joinLikeSync(lastUsedProvider.resolveIdentity()));
}
List<String> exceptionMessages = null;
for (IdentityProvider<? extends AwsCredentialsIdentity> provider : credentialsProviders) {
try {
AwsCredentialsIdentity credentials = CompletableFutureUtils.joinLikeSync(provider.resolveIdentity());
log.debug(() -> "Loading credentials from " + provider);
lastUsedProvider = provider;
return CredentialUtils.toCredentials(credentials);
} catch (RuntimeException e) {
// Ignore any exceptions and move onto the next provider
String message = provider + ": " + e.getMessage();
log.debug(() -> "Unable to load credentials from " + message , e);
if (exceptionMessages == null) {
exceptionMessages = new ArrayList<>();
}
exceptionMessages.add(message);
}
}
throw SdkClientException.builder()
.message("Unable to load credentials from any of the providers in the chain " +
this + " : " + exceptionMessages)
.build();
}
@Override
public void close() {
credentialsProviders.forEach(c -> IoUtils.closeIfCloseable(c, null));
}
@Override
public String toString() {
return ToString.builder("AwsCredentialsProviderChain")
.add("credentialsProviders", credentialsProviders)
.build();
}
@Override
public Builder toBuilder() {
return new BuilderImpl(this);
}
/**
* A builder for a {@link AwsCredentialsProviderChain} that allows controlling its behavior.
*/
public interface Builder extends CopyableBuilder<Builder, AwsCredentialsProviderChain> {
/**
* Controls whether the chain should reuse the last successful credentials provider in the chain. Reusing the last
* successful credentials provider will typically return credentials faster than searching through the chain.
*
* <p>
* By default, this is enabled
*/
Builder reuseLastProviderEnabled(Boolean reuseLastProviderEnabled);
/**
* Configure the credentials providers that should be checked for credentials, in the order they should be checked.
*/
Builder credentialsProviders(Collection<? extends AwsCredentialsProvider> credentialsProviders);
/**
* Configure the credentials providers that should be checked for credentials, in the order they should be checked.
*/
Builder credentialsIdentityProviders(
Collection<? extends IdentityProvider<? extends AwsCredentialsIdentity>> credentialsProviders);
/**
* Configure the credentials providers that should be checked for credentials, in the order they should be checked.
*/
default Builder credentialsProviders(AwsCredentialsProvider... credentialsProviders) {
return credentialsProviders((IdentityProvider<? extends AwsCredentialsIdentity>[]) credentialsProviders);
}
/**
* Configure the credentials providers that should be checked for credentials, in the order they should be checked.
*/
default Builder credentialsProviders(IdentityProvider<? extends AwsCredentialsIdentity>... credentialsProviders) {
throw new UnsupportedOperationException();
}
/**
* Add a credential provider to the chain, after the credential providers that have already been configured.
*/
default Builder addCredentialsProvider(AwsCredentialsProvider credentialsProvider) {
return addCredentialsProvider((IdentityProvider<? extends AwsCredentialsIdentity>) credentialsProvider);
}
/**
* Add a credential provider to the chain, after the credential providers that have already been configured.
*/
default Builder addCredentialsProvider(IdentityProvider<? extends AwsCredentialsIdentity> credentialsProvider) {
throw new UnsupportedOperationException();
}
AwsCredentialsProviderChain build();
}
private static final class BuilderImpl implements Builder {
private Boolean reuseLastProviderEnabled = true;
private List<IdentityProvider<? extends AwsCredentialsIdentity>> credentialsProviders = new ArrayList<>();
private BuilderImpl() {
}
private BuilderImpl(AwsCredentialsProviderChain provider) {
this.reuseLastProviderEnabled = provider.reuseLastProviderEnabled;
this.credentialsProviders = provider.credentialsProviders;
}
@Override
public Builder reuseLastProviderEnabled(Boolean reuseLastProviderEnabled) {
this.reuseLastProviderEnabled = reuseLastProviderEnabled;
return this;
}
public void setReuseLastProviderEnabled(Boolean reuseLastProviderEnabled) {
reuseLastProviderEnabled(reuseLastProviderEnabled);
}
@Override
public Builder credentialsProviders(Collection<? extends AwsCredentialsProvider> credentialsProviders) {
this.credentialsProviders = new ArrayList<>(credentialsProviders);
return this;
}
public void setCredentialsProviders(Collection<? extends AwsCredentialsProvider> credentialsProviders) {
credentialsProviders(credentialsProviders);
}
@Override
public Builder credentialsIdentityProviders(
Collection<? extends IdentityProvider<? extends AwsCredentialsIdentity>> credentialsProviders) {
this.credentialsProviders = new ArrayList<>(credentialsProviders);
return this;
}
public void setCredentialsIdentityProviders(
Collection<? extends IdentityProvider<? extends AwsCredentialsIdentity>> credentialsProviders) {
credentialsIdentityProviders(credentialsProviders);
}
@Override
public Builder credentialsProviders(IdentityProvider<? extends AwsCredentialsIdentity>... credentialsProviders) {
return credentialsIdentityProviders(Arrays.asList(credentialsProviders));
}
@Override
public Builder addCredentialsProvider(IdentityProvider<? extends AwsCredentialsIdentity> credentialsProvider) {
this.credentialsProviders.add(credentialsProvider);
return this;
}
@Override
public AwsCredentialsProviderChain build() {
return new AwsCredentialsProviderChain(this);
}
}
}
| 1,757 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/credentials/TokenUtils.java | /*
* 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.auth.credentials;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.auth.token.credentials.SdkToken;
import software.amazon.awssdk.auth.token.credentials.SdkTokenProvider;
import software.amazon.awssdk.identity.spi.IdentityProvider;
import software.amazon.awssdk.identity.spi.TokenIdentity;
import software.amazon.awssdk.utils.CompletableFutureUtils;
@SdkProtectedApi
public final class TokenUtils {
private TokenUtils() {
}
/**
* Converts an {@link TokenIdentity} to {@link SdkToken}.
*
* <p>Usage of the new TokenIdentity type is preferred over SdkToken. But some places may need to still
* convert to the older SdkToken type to work with existing code.</p>
*
* <p>The conversion is only aware of {@link TokenIdentity} interface. If the input is another sub-type that has other
* properties, they are not carried over.
* </p>
*
* @param tokenIdentity The {@link TokenIdentity} to convert
* @return The corresponding {@link SdkToken}
*/
public static SdkToken toSdkToken(TokenIdentity tokenIdentity) {
if (tokenIdentity == null) {
return null;
}
if (tokenIdentity instanceof SdkToken) {
return (SdkToken) tokenIdentity;
}
return () -> tokenIdentity.token();
}
/**
* Converts an {@link IdentityProvider<? extends TokenIdentity>} to {@link SdkTokenProvider} based on
* {@link #toSdkToken(TokenIdentity)}.
*
* <p>Usage of the new IdentityProvider type is preferred over SdkTokenProvider. But some places may need to still
* convert to the older SdkTokenProvider type to work with existing code.
* </p>
*
* @param identityProvider The {@link IdentityProvider<? extends TokenIdentity>} to convert
* @return The corresponding {@link SdkTokenProvider}
*/
public static SdkTokenProvider toSdkTokenProvider(
IdentityProvider<? extends TokenIdentity> identityProvider) {
if (identityProvider == null) {
return null;
}
if (identityProvider instanceof SdkTokenProvider) {
return (SdkTokenProvider) identityProvider;
}
return () -> toSdkToken(CompletableFutureUtils.joinLikeSync(identityProvider.resolveIdentity()));
}
}
| 1,758 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/credentials/SystemPropertyCredentialsProvider.java | /*
* 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.auth.credentials;
import java.util.Optional;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.auth.credentials.internal.SystemSettingsCredentialsProvider;
import software.amazon.awssdk.utils.SystemSetting;
import software.amazon.awssdk.utils.ToString;
/**
* {@link AwsCredentialsProvider} implementation that loads credentials from the aws.accessKeyId, aws.secretAccessKey and
* aws.sessionToken system properties.
*/
@SdkPublicApi
public final class SystemPropertyCredentialsProvider extends SystemSettingsCredentialsProvider {
private SystemPropertyCredentialsProvider() {
}
public static SystemPropertyCredentialsProvider create() {
return new SystemPropertyCredentialsProvider();
}
@Override
protected Optional<String> loadSetting(SystemSetting setting) {
// CHECKSTYLE:OFF - Customers should be able to specify a credentials provider that only looks at the system properties,
// but not the environment variables. For that reason, we're only checking the system properties here.
return Optional.ofNullable(System.getProperty(setting.property()));
// CHECKSTYLE:ON
}
@Override
public String toString() {
return ToString.create("SystemPropertyCredentialsProvider");
}
}
| 1,759 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/credentials/ChildProfileCredentialsProviderFactory.java | /*
* 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.auth.credentials;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.profiles.Profile;
/**
* A factory for {@link AwsCredentialsProvider}s that are derived from another set of credentials in a profile file.
*
* Currently this is used to allow a {@link Profile} configured with a role that should be assumed to create a credentials
* provider via the 'software.amazon.awssdk.services.sts.internal.StsProfileCredentialsProviderFactory', assuming STS is on the
* classpath.
*/
@FunctionalInterface
@SdkProtectedApi
public interface ChildProfileCredentialsProviderFactory {
/**
* Create a credentials provider for the provided profile, using the provided source credentials provider to authenticate
* with AWS. In the case of STS, the returned credentials provider is for a role that has been assumed, and the provided
* source credentials provider is the credentials that should be used to authenticate that the user is allowed to assume
* that role.
*
* @param sourceCredentialsProvider The credentials provider that should be used to authenticate the child credentials
* provider. This credentials provider should be closed when it is no longer used.
* @param profile The profile that should be used to load the configuration necessary to create the child credentials
* provider.
* @return The credentials provider with permissions derived from the source credentials provider and profile.
*/
AwsCredentialsProvider create(AwsCredentialsProvider sourceCredentialsProvider, Profile profile);
}
| 1,760 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/credentials/AnonymousCredentialsProvider.java | /*
* 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.auth.credentials;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.utils.ToString;
/**
* Credentials provider that always returns anonymous {@link AwsCredentials}. Anonymous AWS credentials result in un-authenticated
* requests and will fail unless the resource or API's policy has been configured to specifically allow anonymous access.
*/
@SdkPublicApi
public final class AnonymousCredentialsProvider implements AwsCredentialsProvider {
private AnonymousCredentialsProvider() {
}
public static AnonymousCredentialsProvider create() {
return new AnonymousCredentialsProvider();
}
@Override
public AwsCredentials resolveCredentials() {
return AwsBasicCredentials.ANONYMOUS_CREDENTIALS;
}
@Override
public String toString() {
return ToString.create("AnonymousCredentialsProvider");
}
}
| 1,761 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/credentials/ContainerCredentialsProvider.java | /*
* 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.auth.credentials;
import java.io.IOException;
import java.net.InetAddress;
import java.net.URI;
import java.net.UnknownHostException;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.function.Predicate;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.auth.credentials.internal.ContainerCredentialsRetryPolicy;
import software.amazon.awssdk.auth.credentials.internal.HttpCredentialsLoader;
import software.amazon.awssdk.auth.credentials.internal.HttpCredentialsLoader.LoadedCredentials;
import software.amazon.awssdk.core.SdkSystemSetting;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.core.util.SdkUserAgent;
import software.amazon.awssdk.regions.util.ResourcesEndpointProvider;
import software.amazon.awssdk.regions.util.ResourcesEndpointRetryPolicy;
import software.amazon.awssdk.utils.ComparableUtils;
import software.amazon.awssdk.utils.StringUtils;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.Validate;
import software.amazon.awssdk.utils.builder.CopyableBuilder;
import software.amazon.awssdk.utils.builder.ToCopyableBuilder;
import software.amazon.awssdk.utils.cache.CachedSupplier;
import software.amazon.awssdk.utils.cache.NonBlocking;
import software.amazon.awssdk.utils.cache.RefreshResult;
/**
* {@link AwsCredentialsProvider} implementation that loads credentials from a local metadata service.
*
* Currently supported containers:
* <ul>
* <li>Amazon Elastic Container Service (ECS)</li>
* <li>AWS Greengrass</li>
* </ul>
*
* <p>The URI path is retrieved from the environment variable "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI" or
* "AWS_CONTAINER_CREDENTIALS_FULL_URI" in the container's environment. If the environment variable is not set, this credentials
* provider will throw an exception.</p>
*
* @see <a href="http://docs.aws.amazon.com/AmazonECS/latest/developerguide/task-iam-roles.html">Amazon Elastic Container
* Service (ECS)</a>
*/
@SdkPublicApi
public final class ContainerCredentialsProvider
implements HttpCredentialsProvider,
ToCopyableBuilder<ContainerCredentialsProvider.Builder, ContainerCredentialsProvider> {
private static final Predicate<InetAddress> IS_LOOPBACK_ADDRESS = InetAddress::isLoopbackAddress;
private static final Predicate<InetAddress> ALLOWED_HOSTS_RULES = IS_LOOPBACK_ADDRESS;
private static final String HTTPS = "https";
private final String endpoint;
private final HttpCredentialsLoader httpCredentialsLoader;
private final CachedSupplier<AwsCredentials> credentialsCache;
private final Boolean asyncCredentialUpdateEnabled;
private final String asyncThreadName;
/**
* @see #builder()
*/
private ContainerCredentialsProvider(BuilderImpl builder) {
this.endpoint = builder.endpoint;
this.asyncCredentialUpdateEnabled = builder.asyncCredentialUpdateEnabled;
this.asyncThreadName = builder.asyncThreadName;
this.httpCredentialsLoader = HttpCredentialsLoader.create();
if (Boolean.TRUE.equals(builder.asyncCredentialUpdateEnabled)) {
Validate.paramNotBlank(builder.asyncThreadName, "asyncThreadName");
this.credentialsCache = CachedSupplier.builder(this::refreshCredentials)
.cachedValueName(toString())
.prefetchStrategy(new NonBlocking(builder.asyncThreadName))
.build();
} else {
this.credentialsCache = CachedSupplier.builder(this::refreshCredentials)
.cachedValueName(toString())
.build();
}
}
/**
* Create a builder for creating a {@link ContainerCredentialsProvider}.
*/
public static Builder builder() {
return new BuilderImpl();
}
@Override
public String toString() {
return ToString.create("ContainerCredentialsProvider");
}
private RefreshResult<AwsCredentials> refreshCredentials() {
LoadedCredentials loadedCredentials =
httpCredentialsLoader.loadCredentials(new ContainerCredentialsEndpointProvider(endpoint));
Instant expiration = loadedCredentials.getExpiration().orElse(null);
return RefreshResult.builder(loadedCredentials.getAwsCredentials())
.staleTime(staleTime(expiration))
.prefetchTime(prefetchTime(expiration))
.build();
}
private Instant staleTime(Instant expiration) {
if (expiration == null) {
return null;
}
return expiration.minus(1, ChronoUnit.MINUTES);
}
private Instant prefetchTime(Instant expiration) {
Instant oneHourFromNow = Instant.now().plus(1, ChronoUnit.HOURS);
if (expiration == null) {
return oneHourFromNow;
}
Instant fifteenMinutesBeforeExpiration = expiration.minus(15, ChronoUnit.MINUTES);
return ComparableUtils.minimum(oneHourFromNow, fifteenMinutesBeforeExpiration);
}
@Override
public AwsCredentials resolveCredentials() {
return credentialsCache.get();
}
@Override
public void close() {
credentialsCache.close();
}
@Override
public Builder toBuilder() {
return new BuilderImpl(this);
}
static final class ContainerCredentialsEndpointProvider implements ResourcesEndpointProvider {
private final String endpoint;
ContainerCredentialsEndpointProvider(String endpoint) {
this.endpoint = endpoint;
}
@Override
public URI endpoint() throws IOException {
if (!SdkSystemSetting.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI.getStringValue().isPresent() &&
!SdkSystemSetting.AWS_CONTAINER_CREDENTIALS_FULL_URI.getStringValue().isPresent()) {
throw SdkClientException.builder()
.message(String.format("Cannot fetch credentials from container - neither %s or %s " +
"environment variables are set.",
SdkSystemSetting.AWS_CONTAINER_CREDENTIALS_FULL_URI.environmentVariable(),
SdkSystemSetting.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI.environmentVariable()))
.build();
}
try {
return SdkSystemSetting.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI.getStringValue()
.map(this::createUri)
.orElseGet(this::createGenericContainerUrl);
} catch (SdkClientException e) {
throw e;
} catch (Exception e) {
throw SdkClientException.builder()
.message("Unable to fetch credentials from container.")
.cause(e)
.build();
}
}
@Override
public ResourcesEndpointRetryPolicy retryPolicy() {
return new ContainerCredentialsRetryPolicy();
}
@Override
public Map<String, String> headers() {
Map<String, String> requestHeaders = new HashMap<>();
requestHeaders.put("User-Agent", SdkUserAgent.create().userAgent());
SdkSystemSetting.AWS_CONTAINER_AUTHORIZATION_TOKEN.getStringValue()
.filter(StringUtils::isNotBlank)
.ifPresent(t -> requestHeaders.put("Authorization", t));
return requestHeaders;
}
private URI createUri(String relativeUri) {
String host = endpoint != null ? endpoint : SdkSystemSetting.AWS_CONTAINER_SERVICE_ENDPOINT.getStringValueOrThrow();
return URI.create(host + relativeUri);
}
private URI createGenericContainerUrl() {
URI uri = URI.create(SdkSystemSetting.AWS_CONTAINER_CREDENTIALS_FULL_URI.getStringValueOrThrow());
if (!isHttps(uri) && !isAllowedHost(uri.getHost())) {
String envVarName = SdkSystemSetting.AWS_CONTAINER_CREDENTIALS_FULL_URI.environmentVariable();
throw SdkClientException.builder()
.message(String.format("The full URI (%s) contained within environment variable " +
"%s has an invalid host. Host should resolve to a loopback " +
"address or have the full URI be HTTPS.",
uri, envVarName))
.build();
}
return uri;
}
private boolean isHttps(URI endpoint) {
return Objects.equals(HTTPS, endpoint.getScheme());
}
/**
* Determines if the addresses for a given host are resolved to a loopback address.
* <p>
* This is a best-effort in determining what address a host will be resolved to. DNS caching might be disabled,
* or could expire between this check and when the API is invoked.
* </p>
* @param host The name or IP address of the host.
* @return A boolean specifying whether the host is allowed as an endpoint for credentials loading.
*/
private boolean isAllowedHost(String host) {
try {
InetAddress[] addresses = InetAddress.getAllByName(host);
return addresses.length > 0 && Arrays.stream(addresses)
.allMatch(this::matchesAllowedHostRules);
} catch (UnknownHostException e) {
throw SdkClientException.builder()
.cause(e)
.message(String.format("host (%s) could not be resolved to an IP address.", host))
.build();
}
}
private boolean matchesAllowedHostRules(InetAddress inetAddress) {
return ALLOWED_HOSTS_RULES.test(inetAddress);
}
}
/**
* A builder for creating a custom a {@link ContainerCredentialsProvider}.
*/
public interface Builder extends HttpCredentialsProvider.Builder<ContainerCredentialsProvider, Builder>,
CopyableBuilder<Builder, ContainerCredentialsProvider> {
}
private static final class BuilderImpl implements Builder {
private String endpoint;
private Boolean asyncCredentialUpdateEnabled;
private String asyncThreadName;
private BuilderImpl() {
asyncThreadName("container-credentials-provider");
}
private BuilderImpl(ContainerCredentialsProvider credentialsProvider) {
this.endpoint = credentialsProvider.endpoint;
this.asyncCredentialUpdateEnabled = credentialsProvider.asyncCredentialUpdateEnabled;
this.asyncThreadName = credentialsProvider.asyncThreadName;
}
@Override
public Builder endpoint(String endpoint) {
this.endpoint = endpoint;
return this;
}
public void setEndpoint(String endpoint) {
endpoint(endpoint);
}
@Override
public Builder asyncCredentialUpdateEnabled(Boolean asyncCredentialUpdateEnabled) {
this.asyncCredentialUpdateEnabled = asyncCredentialUpdateEnabled;
return this;
}
public void setAsyncCredentialUpdateEnabled(boolean asyncCredentialUpdateEnabled) {
asyncCredentialUpdateEnabled(asyncCredentialUpdateEnabled);
}
@Override
public Builder asyncThreadName(String asyncThreadName) {
this.asyncThreadName = asyncThreadName;
return this;
}
public void setAsyncThreadName(String asyncThreadName) {
asyncThreadName(asyncThreadName);
}
@Override
public ContainerCredentialsProvider build() {
return new ContainerCredentialsProvider(this);
}
}
}
| 1,762 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/credentials/AwsSessionCredentials.java | /*
* 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.auth.credentials;
import java.time.Instant;
import java.util.Objects;
import java.util.Optional;
import software.amazon.awssdk.annotations.Immutable;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.identity.spi.AwsSessionCredentialsIdentity;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.Validate;
/**
* A special type of {@link AwsCredentials} that provides a session token to be used in service authentication. Session
* tokens are typically provided by a token broker service, like AWS Security Token Service, and provide temporary access to an
* AWS service.
*/
@Immutable
@SdkPublicApi
public final class AwsSessionCredentials implements AwsCredentials, AwsSessionCredentialsIdentity {
private final String accessKeyId;
private final String secretAccessKey;
private final String sessionToken;
private final Instant expirationTime;
private AwsSessionCredentials(Builder builder) {
this.accessKeyId = Validate.paramNotNull(builder.accessKeyId, "accessKey");
this.secretAccessKey = Validate.paramNotNull(builder.secretAccessKey, "secretKey");
this.sessionToken = Validate.paramNotNull(builder.sessionToken, "sessionToken");
this.expirationTime = builder.expirationTime;
}
/**
* Returns a builder for this object.
*/
public static Builder builder() {
return new Builder();
}
/**
* Constructs a new session credentials object, with the specified AWS access key, AWS secret key and AWS session token.
*
* @param accessKey The AWS access key, used to identify the user interacting with AWS.
* @param secretKey The AWS secret access key, used to authenticate the user interacting with AWS.
* @param sessionToken The AWS session token, retrieved from an AWS token service, used for authenticating that this user has
* received temporary permission to access some resource.
*/
public static AwsSessionCredentials create(String accessKey, String secretKey, String sessionToken) {
return builder().accessKeyId(accessKey).secretAccessKey(secretKey).sessionToken(sessionToken).build();
}
/**
* Retrieve the AWS access key, used to identify the user interacting with AWS.
*/
@Override
public String accessKeyId() {
return accessKeyId;
}
/**
* Retrieve the AWS secret access key, used to authenticate the user interacting with AWS.
*/
@Override
public String secretAccessKey() {
return secretAccessKey;
}
/**
* Retrieve the expiration time of these credentials, if it exists.
*/
@Override
public Optional<Instant> expirationTime() {
return Optional.ofNullable(expirationTime);
}
/**
* Retrieve the AWS session token. This token is retrieved from an AWS token service, and is used for authenticating that this
* user has received temporary permission to access some resource.
*/
public String sessionToken() {
return sessionToken;
}
@Override
public String toString() {
return ToString.builder("AwsSessionCredentials")
.add("accessKeyId", accessKeyId())
.build();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
AwsSessionCredentials that = (AwsSessionCredentials) o;
return Objects.equals(accessKeyId, that.accessKeyId) &&
Objects.equals(secretAccessKey, that.secretAccessKey) &&
Objects.equals(sessionToken, that.sessionToken) &&
Objects.equals(expirationTime, that.expirationTime().orElse(null));
}
@Override
public int hashCode() {
int hashCode = 1;
hashCode = 31 * hashCode + Objects.hashCode(accessKeyId());
hashCode = 31 * hashCode + Objects.hashCode(secretAccessKey());
hashCode = 31 * hashCode + Objects.hashCode(sessionToken());
hashCode = 31 * hashCode + Objects.hashCode(expirationTime);
return hashCode;
}
/**
* A builder for creating an instance of {@link AwsSessionCredentials}. This can be created with the static
* {@link #builder()} method.
*/
public static final class Builder {
private String accessKeyId;
private String secretAccessKey;
private String sessionToken;
private Instant expirationTime;
/**
* The AWS access key, used to identify the user interacting with services. Required.
*/
public Builder accessKeyId(String accessKeyId) {
this.accessKeyId = accessKeyId;
return this;
}
/**
* The AWS secret access key, used to authenticate the user interacting with services. Required
*/
public Builder secretAccessKey(String secretAccessKey) {
this.secretAccessKey = secretAccessKey;
return this;
}
/**
* The AWS session token, retrieved from an AWS token service, used for authenticating that this user has
* received temporary permission to access some resource. Required
*/
public Builder sessionToken(String sessionToken) {
this.sessionToken = sessionToken;
return this;
}
/**
* The time after which this identity will no longer be valid. If this is empty,
* an expiration time is not known (but the identity may still expire at some
* time in the future).
*/
public Builder expirationTime(Instant expirationTime) {
this.expirationTime = expirationTime;
return this;
}
public AwsSessionCredentials build() {
return new AwsSessionCredentials(this);
}
}
}
| 1,763 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/credentials/InstanceProfileCredentialsProvider.java | /*
* 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.auth.credentials;
import static java.time.temporal.ChronoUnit.MINUTES;
import static software.amazon.awssdk.utils.ComparableUtils.maximum;
import static software.amazon.awssdk.utils.FunctionalUtils.invokeSafely;
import static software.amazon.awssdk.utils.cache.CachedSupplier.StaleValueBehavior.ALLOW;
import java.net.URI;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.Collections;
import java.util.Map;
import java.util.Optional;
import java.util.function.Supplier;
import software.amazon.awssdk.annotations.SdkPublicApi;
import software.amazon.awssdk.annotations.SdkTestInternalApi;
import software.amazon.awssdk.auth.credentials.internal.Ec2MetadataConfigProvider;
import software.amazon.awssdk.auth.credentials.internal.HttpCredentialsLoader;
import software.amazon.awssdk.auth.credentials.internal.HttpCredentialsLoader.LoadedCredentials;
import software.amazon.awssdk.auth.credentials.internal.StaticResourcesEndpointProvider;
import software.amazon.awssdk.core.SdkSystemSetting;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.core.exception.SdkServiceException;
import software.amazon.awssdk.profiles.ProfileFile;
import software.amazon.awssdk.profiles.ProfileFileSupplier;
import software.amazon.awssdk.profiles.ProfileFileSystemSetting;
import software.amazon.awssdk.regions.util.HttpResourcesUtils;
import software.amazon.awssdk.regions.util.ResourcesEndpointProvider;
import software.amazon.awssdk.utils.Logger;
import software.amazon.awssdk.utils.ToString;
import software.amazon.awssdk.utils.Validate;
import software.amazon.awssdk.utils.builder.CopyableBuilder;
import software.amazon.awssdk.utils.builder.ToCopyableBuilder;
import software.amazon.awssdk.utils.cache.CachedSupplier;
import software.amazon.awssdk.utils.cache.NonBlocking;
import software.amazon.awssdk.utils.cache.RefreshResult;
/**
* Credentials provider implementation that loads credentials from the Amazon EC2 Instance Metadata Service.
*
* <P>
* If {@link SdkSystemSetting#AWS_EC2_METADATA_DISABLED} is set to true, it will not try to load
* credentials from EC2 metadata service and will return null.
*/
@SdkPublicApi
public final class InstanceProfileCredentialsProvider
implements HttpCredentialsProvider,
ToCopyableBuilder<InstanceProfileCredentialsProvider.Builder, InstanceProfileCredentialsProvider> {
private static final Logger log = Logger.loggerFor(InstanceProfileCredentialsProvider.class);
private static final String EC2_METADATA_TOKEN_HEADER = "x-aws-ec2-metadata-token";
private static final String SECURITY_CREDENTIALS_RESOURCE = "/latest/meta-data/iam/security-credentials/";
private static final String TOKEN_RESOURCE = "/latest/api/token";
private static final String EC2_METADATA_TOKEN_TTL_HEADER = "x-aws-ec2-metadata-token-ttl-seconds";
private static final String DEFAULT_TOKEN_TTL = "21600";
private final Clock clock;
private final String endpoint;
private final Ec2MetadataConfigProvider configProvider;
private final HttpCredentialsLoader httpCredentialsLoader;
private final CachedSupplier<AwsCredentials> credentialsCache;
private final Boolean asyncCredentialUpdateEnabled;
private final String asyncThreadName;
private final Supplier<ProfileFile> profileFile;
private final String profileName;
/**
* @see #builder()
*/
private InstanceProfileCredentialsProvider(BuilderImpl builder) {
this.clock = builder.clock;
this.endpoint = builder.endpoint;
this.asyncCredentialUpdateEnabled = builder.asyncCredentialUpdateEnabled;
this.asyncThreadName = builder.asyncThreadName;
this.profileFile = builder.profileFile;
this.profileName = builder.profileName;
this.httpCredentialsLoader = HttpCredentialsLoader.create();
this.configProvider =
Ec2MetadataConfigProvider.builder()
.profileFile(builder.profileFile)
.profileName(builder.profileName)
.build();
if (Boolean.TRUE.equals(builder.asyncCredentialUpdateEnabled)) {
Validate.paramNotBlank(builder.asyncThreadName, "asyncThreadName");
this.credentialsCache = CachedSupplier.builder(this::refreshCredentials)
.cachedValueName(toString())
.prefetchStrategy(new NonBlocking(builder.asyncThreadName))
.staleValueBehavior(ALLOW)
.clock(clock)
.build();
} else {
this.credentialsCache = CachedSupplier.builder(this::refreshCredentials)
.cachedValueName(toString())
.staleValueBehavior(ALLOW)
.clock(clock)
.build();
}
}
/**
* Create a builder for creating a {@link InstanceProfileCredentialsProvider}.
*/
public static Builder builder() {
return new BuilderImpl();
}
/**
* Create a {@link InstanceProfileCredentialsProvider} with default values.
*
* @return a {@link InstanceProfileCredentialsProvider}
*/
public static InstanceProfileCredentialsProvider create() {
return builder().build();
}
@Override
public AwsCredentials resolveCredentials() {
return credentialsCache.get();
}
private RefreshResult<AwsCredentials> refreshCredentials() {
if (isLocalCredentialLoadingDisabled()) {
throw SdkClientException.create("IMDS credentials have been disabled by environment variable or system property.");
}
try {
LoadedCredentials credentials = httpCredentialsLoader.loadCredentials(createEndpointProvider());
Instant expiration = credentials.getExpiration().orElse(null);
log.debug(() -> "Loaded credentials from IMDS with expiration time of " + expiration);
return RefreshResult.builder(credentials.getAwsCredentials())
.staleTime(staleTime(expiration))
.prefetchTime(prefetchTime(expiration))
.build();
} catch (RuntimeException e) {
throw SdkClientException.create("Failed to load credentials from IMDS.", e);
}
}
private boolean isLocalCredentialLoadingDisabled() {
return SdkSystemSetting.AWS_EC2_METADATA_DISABLED.getBooleanValueOrThrow();
}
private Instant staleTime(Instant expiration) {
if (expiration == null) {
return null;
}
return expiration.minusSeconds(1);
}
private Instant prefetchTime(Instant expiration) {
Instant now = clock.instant();
if (expiration == null) {
return now.plus(60, MINUTES);
}
Duration timeUntilExpiration = Duration.between(now, expiration);
if (timeUntilExpiration.isNegative()) {
// IMDS gave us a time in the past. We're already stale. Don't prefetch.
return null;
}
return now.plus(maximum(timeUntilExpiration.dividedBy(2), Duration.ofMinutes(5)));
}
@Override
public void close() {
credentialsCache.close();
}
@Override
public String toString() {
return ToString.create("InstanceProfileCredentialsProvider");
}
private ResourcesEndpointProvider createEndpointProvider() {
String imdsHostname = getImdsEndpoint();
String token = getToken(imdsHostname);
String[] securityCredentials = getSecurityCredentials(imdsHostname, token);
return new StaticResourcesEndpointProvider(URI.create(imdsHostname + SECURITY_CREDENTIALS_RESOURCE +
securityCredentials[0]),
getTokenHeaders(token));
}
private String getImdsEndpoint() {
if (endpoint != null) {
return endpoint;
}
return configProvider.getEndpoint();
}
private String getToken(String imdsHostname) {
Map<String, String> tokenTtlHeaders = Collections.singletonMap(EC2_METADATA_TOKEN_TTL_HEADER, DEFAULT_TOKEN_TTL);
ResourcesEndpointProvider tokenEndpoint = new StaticResourcesEndpointProvider(getTokenEndpoint(imdsHostname),
tokenTtlHeaders);
try {
return HttpResourcesUtils.instance().readResource(tokenEndpoint, "PUT");
} catch (SdkServiceException e) {
if (e.statusCode() == 400) {
throw SdkClientException.builder()
.message("Unable to fetch metadata token.")
.cause(e)
.build();
}
log.debug(() -> "Ignoring non-fatal exception while attempting to load metadata token from instance profile.", e);
return null;
} catch (Exception e) {
log.debug(() -> "Ignoring non-fatal exception while attempting to load metadata token from instance profile.", e);
return null;
}
}
private URI getTokenEndpoint(String imdsHostname) {
String finalHost = imdsHostname;
if (finalHost.endsWith("/")) {
finalHost = finalHost.substring(0, finalHost.length() - 1);
}
return URI.create(finalHost + TOKEN_RESOURCE);
}
private String[] getSecurityCredentials(String imdsHostname, String metadataToken) {
ResourcesEndpointProvider securityCredentialsEndpoint =
new StaticResourcesEndpointProvider(URI.create(imdsHostname + SECURITY_CREDENTIALS_RESOURCE),
getTokenHeaders(metadataToken));
String securityCredentialsList =
invokeSafely(() -> HttpResourcesUtils.instance().readResource(securityCredentialsEndpoint));
String[] securityCredentials = securityCredentialsList.trim().split("\n");
if (securityCredentials.length == 0) {
throw SdkClientException.builder().message("Unable to load credentials path").build();
}
return securityCredentials;
}
private Map<String, String> getTokenHeaders(String metadataToken) {
if (metadataToken == null) {
return Collections.emptyMap();
}
return Collections.singletonMap(EC2_METADATA_TOKEN_HEADER, metadataToken);
}
@Override
public Builder toBuilder() {
return new BuilderImpl(this);
}
/**
* A builder for creating a custom a {@link InstanceProfileCredentialsProvider}.
*/
public interface Builder extends HttpCredentialsProvider.Builder<InstanceProfileCredentialsProvider, Builder>,
CopyableBuilder<Builder, InstanceProfileCredentialsProvider> {
/**
* Configure the profile file used for loading IMDS-related configuration, like the endpoint mode (IPv4 vs IPv6).
*
* <p>By default, {@link ProfileFile#defaultProfileFile()} is used.
*
* @see #profileFile(Supplier)
*/
Builder profileFile(ProfileFile profileFile);
/**
* Define the mechanism for loading profile files.
*
* @param profileFileSupplier Supplier interface for generating a ProfileFile instance.
* @see #profileFile(ProfileFile)
*/
Builder profileFile(Supplier<ProfileFile> profileFileSupplier);
/**
* Configure the profile name used for loading IMDS-related configuration, like the endpoint mode (IPv4 vs IPv6).
*
* <p>By default, {@link ProfileFileSystemSetting#AWS_PROFILE} is used.
*/
Builder profileName(String profileName);
/**
* Build a {@link InstanceProfileCredentialsProvider} from the provided configuration.
*/
@Override
InstanceProfileCredentialsProvider build();
}
@SdkTestInternalApi
static final class BuilderImpl implements Builder {
private Clock clock = Clock.systemUTC();
private String endpoint;
private Boolean asyncCredentialUpdateEnabled;
private String asyncThreadName;
private Supplier<ProfileFile> profileFile;
private String profileName;
private BuilderImpl() {
asyncThreadName("instance-profile-credentials-provider");
}
private BuilderImpl(InstanceProfileCredentialsProvider provider) {
this.clock = provider.clock;
this.endpoint = provider.endpoint;
this.asyncCredentialUpdateEnabled = provider.asyncCredentialUpdateEnabled;
this.asyncThreadName = provider.asyncThreadName;
this.profileFile = provider.profileFile;
this.profileName = provider.profileName;
}
Builder clock(Clock clock) {
this.clock = clock;
return this;
}
@Override
public Builder endpoint(String endpoint) {
this.endpoint = endpoint;
return this;
}
public void setEndpoint(String endpoint) {
endpoint(endpoint);
}
@Override
public Builder asyncCredentialUpdateEnabled(Boolean asyncCredentialUpdateEnabled) {
this.asyncCredentialUpdateEnabled = asyncCredentialUpdateEnabled;
return this;
}
public void setAsyncCredentialUpdateEnabled(boolean asyncCredentialUpdateEnabled) {
asyncCredentialUpdateEnabled(asyncCredentialUpdateEnabled);
}
@Override
public Builder asyncThreadName(String asyncThreadName) {
this.asyncThreadName = asyncThreadName;
return this;
}
public void setAsyncThreadName(String asyncThreadName) {
asyncThreadName(asyncThreadName);
}
@Override
public Builder profileFile(ProfileFile profileFile) {
return profileFile(Optional.ofNullable(profileFile)
.map(ProfileFileSupplier::fixedProfileFile)
.orElse(null));
}
public void setProfileFile(ProfileFile profileFile) {
profileFile(profileFile);
}
@Override
public Builder profileFile(Supplier<ProfileFile> profileFileSupplier) {
this.profileFile = profileFileSupplier;
return this;
}
public void setProfileFile(Supplier<ProfileFile> profileFileSupplier) {
profileFile(profileFileSupplier);
}
@Override
public Builder profileName(String profileName) {
this.profileName = profileName;
return this;
}
public void setProfileName(String profileName) {
profileName(profileName);
}
@Override
public InstanceProfileCredentialsProvider build() {
return new InstanceProfileCredentialsProvider(this);
}
}
}
| 1,764 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/credentials | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/credentials/internal/Ec2MetadataConfigProvider.java | /*
* 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.auth.credentials.internal;
import java.util.Optional;
import java.util.function.Supplier;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.core.SdkSystemSetting;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.profiles.Profile;
import software.amazon.awssdk.profiles.ProfileFile;
import software.amazon.awssdk.profiles.ProfileFileSystemSetting;
import software.amazon.awssdk.profiles.ProfileProperty;
@SdkInternalApi
// TODO: Remove or consolidate this class with the one from the regions module.
// There's currently no good way for both auth and regions to share the same
// class since there's no suitable common dependency between the two where this
// can live. Ideally, we can do this when the EC2MetadataUtils is replaced with
// the IMDS client.
public final class Ec2MetadataConfigProvider {
/** Default IPv4 endpoint for the Amazon EC2 Instance Metadata Service. */
private static final String EC2_METADATA_SERVICE_URL_IPV4 = "http://169.254.169.254";
/** Default IPv6 endpoint for the Amazon EC2 Instance Metadata Service. */
private static final String EC2_METADATA_SERVICE_URL_IPV6 = "http://[fd00:ec2::254]";
private final Supplier<ProfileFile> profileFile;
private final String profileName;
private Ec2MetadataConfigProvider(Builder builder) {
this.profileFile = builder.profileFile;
this.profileName = builder.profileName;
}
public enum EndpointMode {
IPV4,
IPV6,
;
public static EndpointMode fromValue(String s) {
if (s == null) {
return null;
}
for (EndpointMode value : EndpointMode.values()) {
if (value.name().equalsIgnoreCase(s)) {
return value;
}
}
throw new IllegalArgumentException("Unrecognized value for endpoint mode: " + s);
}
}
public String getEndpoint() {
String endpointOverride = getEndpointOverride();
if (endpointOverride != null) {
return endpointOverride;
}
EndpointMode endpointMode = getEndpointMode();
switch (endpointMode) {
case IPV4:
return EC2_METADATA_SERVICE_URL_IPV4;
case IPV6:
return EC2_METADATA_SERVICE_URL_IPV6;
default:
throw SdkClientException.create("Unknown endpoint mode: " + endpointMode);
}
}
public EndpointMode getEndpointMode() {
Optional<String> endpointMode = SdkSystemSetting.AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE.getNonDefaultStringValue();
if (endpointMode.isPresent()) {
return EndpointMode.fromValue(endpointMode.get());
}
return configFileEndpointMode().orElseGet(() ->
EndpointMode.fromValue(SdkSystemSetting.AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE.defaultValue()));
}
public String getEndpointOverride() {
Optional<String> endpointOverride = SdkSystemSetting.AWS_EC2_METADATA_SERVICE_ENDPOINT.getNonDefaultStringValue();
if (endpointOverride.isPresent()) {
return endpointOverride.get();
}
Optional<String> configFileValue = configFileEndpointOverride();
return configFileValue.orElse(null);
}
public static Builder builder() {
return new Builder();
}
private Optional<EndpointMode> configFileEndpointMode() {
return resolveProfile().flatMap(p -> p.property(ProfileProperty.EC2_METADATA_SERVICE_ENDPOINT_MODE))
.map(EndpointMode::fromValue);
}
private Optional<String> configFileEndpointOverride() {
return resolveProfile().flatMap(p -> p.property(ProfileProperty.EC2_METADATA_SERVICE_ENDPOINT));
}
private Optional<Profile> resolveProfile() {
ProfileFile profileFileToUse = resolveProfileFile();
String profileNameToUse = resolveProfileName();
return profileFileToUse.profile(profileNameToUse);
}
private ProfileFile resolveProfileFile() {
if (profileFile != null) {
return profileFile.get();
}
return ProfileFile.defaultProfileFile();
}
private String resolveProfileName() {
if (profileName != null) {
return profileName;
}
return ProfileFileSystemSetting.AWS_PROFILE.getStringValueOrThrow();
}
public static class Builder {
private Supplier<ProfileFile> profileFile;
private String profileName;
public Builder profileFile(Supplier<ProfileFile> profileFile) {
this.profileFile = profileFile;
return this;
}
public Builder profileName(String profileName) {
this.profileName = profileName;
return this;
}
public Ec2MetadataConfigProvider build() {
return new Ec2MetadataConfigProvider(this);
}
}
}
| 1,765 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/credentials | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/credentials/internal/SystemSettingsCredentialsProvider.java | /*
* 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.auth.credentials.internal;
import static software.amazon.awssdk.utils.StringUtils.trim;
import java.util.Optional;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.AwsCredentials;
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
import software.amazon.awssdk.auth.credentials.AwsSessionCredentials;
import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider;
import software.amazon.awssdk.auth.credentials.SystemPropertyCredentialsProvider;
import software.amazon.awssdk.core.SdkSystemSetting;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.utils.StringUtils;
import software.amazon.awssdk.utils.SystemSetting;
/**
* Loads credentials providers from the {@link SdkSystemSetting#AWS_ACCESS_KEY_ID},
* {@link SdkSystemSetting#AWS_SECRET_ACCESS_KEY}, and {@link SdkSystemSetting#AWS_SESSION_TOKEN} system settings.
*
* This does not load the credentials directly. Instead, the actual mapping of setting to credentials is done by child classes.
* This allows us to separately load the credentials from system properties and environment variables so that customers can
* remove one or the other from their credential chain, or build a different chain with these pieces of functionality separated.
*
* @see EnvironmentVariableCredentialsProvider
* @see SystemPropertyCredentialsProvider
*/
@SdkInternalApi
public abstract class SystemSettingsCredentialsProvider implements AwsCredentialsProvider {
@Override
public AwsCredentials resolveCredentials() {
String accessKey = trim(loadSetting(SdkSystemSetting.AWS_ACCESS_KEY_ID).orElse(null));
String secretKey = trim(loadSetting(SdkSystemSetting.AWS_SECRET_ACCESS_KEY).orElse(null));
String sessionToken = trim(loadSetting(SdkSystemSetting.AWS_SESSION_TOKEN).orElse(null));
if (StringUtils.isBlank(accessKey)) {
throw SdkClientException.builder()
.message(String.format("Unable to load credentials from system settings. Access key must be" +
" specified either via environment variable (%s) or system property (%s).",
SdkSystemSetting.AWS_ACCESS_KEY_ID.environmentVariable(),
SdkSystemSetting.AWS_ACCESS_KEY_ID.property()))
.build();
}
if (StringUtils.isBlank(secretKey)) {
throw SdkClientException.builder()
.message(String.format("Unable to load credentials from system settings. Secret key must be" +
" specified either via environment variable (%s) or system property (%s).",
SdkSystemSetting.AWS_SECRET_ACCESS_KEY.environmentVariable(),
SdkSystemSetting.AWS_SECRET_ACCESS_KEY.property()))
.build();
}
return StringUtils.isBlank(sessionToken) ? AwsBasicCredentials.create(accessKey, secretKey)
: AwsSessionCredentials.create(accessKey, secretKey, sessionToken);
}
/**
* Implemented by child classes to load the requested setting.
*/
protected abstract Optional<String> loadSetting(SystemSetting setting);
}
| 1,766 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/credentials | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/credentials/internal/HttpCredentialsLoader.java | /*
* 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.auth.credentials.internal;
import java.io.IOException;
import java.time.Instant;
import java.util.Map;
import java.util.Optional;
import java.util.regex.Pattern;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.AwsCredentials;
import software.amazon.awssdk.auth.credentials.AwsSessionCredentials;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.protocols.jsoncore.JsonNode;
import software.amazon.awssdk.protocols.jsoncore.JsonNodeParser;
import software.amazon.awssdk.regions.util.HttpResourcesUtils;
import software.amazon.awssdk.regions.util.ResourcesEndpointProvider;
import software.amazon.awssdk.utils.DateUtils;
import software.amazon.awssdk.utils.Validate;
/**
* Helper class that contains the common behavior of the CredentialsProviders that loads the credentials from a local endpoint on
* a container (e.g. an EC2 instance).
*/
@SdkInternalApi
public final class HttpCredentialsLoader {
private static final JsonNodeParser SENSITIVE_PARSER =
JsonNodeParser.builder()
.removeErrorLocations(true)
.build();
private static final Pattern TRAILING_ZERO_OFFSET_TIME_PATTERN = Pattern.compile("\\+0000$");
private HttpCredentialsLoader() {
}
public static HttpCredentialsLoader create() {
return new HttpCredentialsLoader();
}
public LoadedCredentials loadCredentials(ResourcesEndpointProvider endpoint) {
try {
String credentialsResponse = HttpResourcesUtils.instance().readResource(endpoint);
Map<String, JsonNode> node = SENSITIVE_PARSER.parse(credentialsResponse).asObject();
JsonNode accessKey = node.get("AccessKeyId");
JsonNode secretKey = node.get("SecretAccessKey");
JsonNode token = node.get("Token");
JsonNode expiration = node.get("Expiration");
Validate.notNull(accessKey, "Failed to load access key from metadata service.");
Validate.notNull(secretKey, "Failed to load secret key from metadata service.");
return new LoadedCredentials(accessKey.text(),
secretKey.text(),
token != null ? token.text() : null,
expiration != null ? expiration.text() : null);
} catch (SdkClientException e) {
throw e;
} catch (RuntimeException | IOException e) {
throw SdkClientException.builder()
.message("Failed to load credentials from metadata service.")
.cause(e)
.build();
}
}
public static final class LoadedCredentials {
private final String accessKeyId;
private final String secretKey;
private final String token;
private final Instant expiration;
private LoadedCredentials(String accessKeyId, String secretKey, String token, String expiration) {
this.accessKeyId = Validate.paramNotBlank(accessKeyId, "accessKeyId");
this.secretKey = Validate.paramNotBlank(secretKey, "secretKey");
this.token = token;
this.expiration = expiration == null ? null : parseExpiration(expiration);
}
public AwsCredentials getAwsCredentials() {
if (token == null) {
return AwsBasicCredentials.create(accessKeyId, secretKey);
} else {
return AwsSessionCredentials.create(accessKeyId, secretKey, token);
}
}
public Optional<Instant> getExpiration() {
return Optional.ofNullable(expiration);
}
private static Instant parseExpiration(String expiration) {
if (expiration == null) {
return null;
}
// Convert the expirationNode string to ISO-8601 format.
String expirationValue = TRAILING_ZERO_OFFSET_TIME_PATTERN.matcher(expiration).replaceAll("Z");
try {
return DateUtils.parseIso8601Date(expirationValue);
} catch (RuntimeException e) {
throw new IllegalStateException("Unable to parse credentials expiration date from metadata service.", e);
}
}
}
}
| 1,767 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/credentials | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/credentials/internal/ProfileCredentialsUtils.java | /*
* 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.auth.credentials.internal;
import java.lang.reflect.InvocationTargetException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.AwsCredentials;
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
import software.amazon.awssdk.auth.credentials.AwsCredentialsProviderChain;
import software.amazon.awssdk.auth.credentials.AwsSessionCredentials;
import software.amazon.awssdk.auth.credentials.ChildProfileCredentialsProviderFactory;
import software.amazon.awssdk.auth.credentials.ContainerCredentialsProvider;
import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider;
import software.amazon.awssdk.auth.credentials.InstanceProfileCredentialsProvider;
import software.amazon.awssdk.auth.credentials.ProcessCredentialsProvider;
import software.amazon.awssdk.auth.credentials.ProfileCredentialsProviderFactory;
import software.amazon.awssdk.auth.credentials.ProfileProviderCredentialsContext;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.auth.credentials.SystemPropertyCredentialsProvider;
import software.amazon.awssdk.core.internal.util.ClassLoaderHelper;
import software.amazon.awssdk.profiles.Profile;
import software.amazon.awssdk.profiles.ProfileFile;
import software.amazon.awssdk.profiles.ProfileProperty;
import software.amazon.awssdk.profiles.internal.ProfileSection;
import software.amazon.awssdk.utils.SdkAutoCloseable;
import software.amazon.awssdk.utils.Validate;
/**
* Utility class to load {@link #credentialsProvider()} configured in a profile.
*/
@SdkInternalApi
public final class ProfileCredentialsUtils {
private static final String STS_PROFILE_CREDENTIALS_PROVIDER_FACTORY =
"software.amazon.awssdk.services.sts.internal.StsProfileCredentialsProviderFactory";
private static final String SSO_PROFILE_CREDENTIALS_PROVIDER_FACTORY =
"software.amazon.awssdk.services.sso.auth.SsoProfileCredentialsProviderFactory";
/**
* The profile file containing {@code profile}.
*/
private final ProfileFile profileFile;
private final Profile profile;
/**
* The name of this profile (minus any profile prefixes).
*/
private final String name;
/**
* The raw properties in this profile.
*/
private final Map<String, String> properties;
/**
* A function to resolve the profile from which this profile should derive its credentials.
*
* This is used by assume-role credentials providers to find the credentials it should use for authentication when assuming
* the role.
*/
private final Function<String, Optional<Profile>> credentialsSourceResolver;
public ProfileCredentialsUtils(ProfileFile profileFile,
Profile profile,
Function<String, Optional<Profile>> credentialsSourceResolver) {
this.profileFile = Validate.paramNotNull(profileFile, "profileFile");
this.profile = Validate.paramNotNull(profile, "profile");
this.name = profile.name();
this.properties = profile.properties();
this.credentialsSourceResolver = credentialsSourceResolver;
}
/**
* Retrieve the credentials provider for which this profile has been configured, if available.
*
* If this profile is configured for role-based credential loading, the returned {@link AwsCredentialsProvider} implements
* {@link SdkAutoCloseable} and should be cleaned up to prevent resource leaks in the event that multiple credentials
* providers will be created.
*/
public Optional<AwsCredentialsProvider> credentialsProvider() {
return credentialsProvider(new HashSet<>());
}
/**
* Retrieve the credentials provider for which this profile has been configured, if available.
*
* @param children The child profiles that source credentials from this profile.
*/
private Optional<AwsCredentialsProvider> credentialsProvider(Set<String> children) {
if (properties.containsKey(ProfileProperty.ROLE_ARN) && properties.containsKey(ProfileProperty.WEB_IDENTITY_TOKEN_FILE)) {
return Optional.ofNullable(roleAndWebIdentityTokenProfileCredentialsProvider());
}
if (properties.containsKey(ProfileProperty.SSO_ROLE_NAME)
|| properties.containsKey(ProfileProperty.SSO_ACCOUNT_ID)
|| properties.containsKey(ProfileProperty.SSO_REGION)
|| properties.containsKey(ProfileProperty.SSO_START_URL)
|| properties.containsKey(ProfileSection.SSO_SESSION.getPropertyKeyName())) {
return Optional.ofNullable(ssoProfileCredentialsProvider());
}
if (properties.containsKey(ProfileProperty.ROLE_ARN)) {
boolean hasSourceProfile = properties.containsKey(ProfileProperty.SOURCE_PROFILE);
boolean hasCredentialSource = properties.containsKey(ProfileProperty.CREDENTIAL_SOURCE);
Validate.validState(!(hasSourceProfile && hasCredentialSource),
"Invalid profile file: profile has both %s and %s.",
ProfileProperty.SOURCE_PROFILE, ProfileProperty.CREDENTIAL_SOURCE);
if (hasSourceProfile) {
return Optional.ofNullable(roleAndSourceProfileBasedProfileCredentialsProvider(children));
}
if (hasCredentialSource) {
return Optional.ofNullable(roleAndCredentialSourceBasedProfileCredentialsProvider());
}
}
if (properties.containsKey(ProfileProperty.CREDENTIAL_PROCESS)) {
return Optional.ofNullable(credentialProcessCredentialsProvider());
}
if (properties.containsKey(ProfileProperty.AWS_SESSION_TOKEN)) {
return Optional.of(sessionProfileCredentialsProvider());
}
if (properties.containsKey(ProfileProperty.AWS_ACCESS_KEY_ID)) {
return Optional.of(basicProfileCredentialsProvider());
}
return Optional.empty();
}
/**
* Load a basic set of credentials that have been configured in this profile.
*/
private AwsCredentialsProvider basicProfileCredentialsProvider() {
requireProperties(ProfileProperty.AWS_ACCESS_KEY_ID,
ProfileProperty.AWS_SECRET_ACCESS_KEY);
AwsCredentials credentials = AwsBasicCredentials.create(properties.get(ProfileProperty.AWS_ACCESS_KEY_ID),
properties.get(ProfileProperty.AWS_SECRET_ACCESS_KEY));
return StaticCredentialsProvider.create(credentials);
}
/**
* Load a set of session credentials that have been configured in this profile.
*/
private AwsCredentialsProvider sessionProfileCredentialsProvider() {
requireProperties(ProfileProperty.AWS_ACCESS_KEY_ID,
ProfileProperty.AWS_SECRET_ACCESS_KEY,
ProfileProperty.AWS_SESSION_TOKEN);
AwsCredentials credentials = AwsSessionCredentials.create(properties.get(ProfileProperty.AWS_ACCESS_KEY_ID),
properties.get(ProfileProperty.AWS_SECRET_ACCESS_KEY),
properties.get(ProfileProperty.AWS_SESSION_TOKEN));
return StaticCredentialsProvider.create(credentials);
}
private AwsCredentialsProvider credentialProcessCredentialsProvider() {
requireProperties(ProfileProperty.CREDENTIAL_PROCESS);
return ProcessCredentialsProvider.builder()
.command(properties.get(ProfileProperty.CREDENTIAL_PROCESS))
.build();
}
/**
* Create the SSO credentials provider based on the related profile properties.
*/
private AwsCredentialsProvider ssoProfileCredentialsProvider() {
validateRequiredPropertiesForSsoCredentialsProvider();
return ssoCredentialsProviderFactory().create(
ProfileProviderCredentialsContext.builder()
.profile(profile)
.profileFile(profileFile)
.build());
}
private void validateRequiredPropertiesForSsoCredentialsProvider() {
requireProperties(ProfileProperty.SSO_ACCOUNT_ID,
ProfileProperty.SSO_ROLE_NAME);
if (!properties.containsKey(ProfileSection.SSO_SESSION.getPropertyKeyName())) {
requireProperties(ProfileProperty.SSO_REGION, ProfileProperty.SSO_START_URL);
}
}
private AwsCredentialsProvider roleAndWebIdentityTokenProfileCredentialsProvider() {
requireProperties(ProfileProperty.ROLE_ARN, ProfileProperty.WEB_IDENTITY_TOKEN_FILE);
String roleArn = properties.get(ProfileProperty.ROLE_ARN);
String roleSessionName = properties.get(ProfileProperty.ROLE_SESSION_NAME);
Path webIdentityTokenFile = Paths.get(properties.get(ProfileProperty.WEB_IDENTITY_TOKEN_FILE));
WebIdentityTokenCredentialProperties credentialProperties =
WebIdentityTokenCredentialProperties.builder()
.roleArn(roleArn)
.roleSessionName(roleSessionName)
.webIdentityTokenFile(webIdentityTokenFile)
.build();
return WebIdentityCredentialsUtils.factory().create(credentialProperties);
}
/**
* Load an assumed-role credentials provider that has been configured in this profile. This will attempt to locate the STS
* module in order to generate the credentials provider. If it's not available, an illegal state exception will be raised.
*
* @param children The child profiles that source credentials from this profile.
*/
private AwsCredentialsProvider roleAndSourceProfileBasedProfileCredentialsProvider(Set<String> children) {
requireProperties(ProfileProperty.SOURCE_PROFILE);
Validate.validState(!children.contains(name),
"Invalid profile file: Circular relationship detected with profiles %s.", children);
Validate.validState(credentialsSourceResolver != null,
"The profile '%s' must be configured with a source profile in order to use assumed roles.", name);
children.add(name);
AwsCredentialsProvider sourceCredentialsProvider =
credentialsSourceResolver.apply(properties.get(ProfileProperty.SOURCE_PROFILE))
.flatMap(p -> new ProfileCredentialsUtils(profileFile, p, credentialsSourceResolver)
.credentialsProvider(children))
.orElseThrow(this::noSourceCredentialsException);
return stsCredentialsProviderFactory().create(sourceCredentialsProvider, profile);
}
/**
* Load an assumed-role credentials provider that has been configured in this profile. This will attempt to locate the STS
* module in order to generate the credentials provider. If it's not available, an illegal state exception will be raised.
*/
private AwsCredentialsProvider roleAndCredentialSourceBasedProfileCredentialsProvider() {
requireProperties(ProfileProperty.CREDENTIAL_SOURCE);
CredentialSourceType credentialSource = CredentialSourceType.parse(properties.get(ProfileProperty.CREDENTIAL_SOURCE));
AwsCredentialsProvider credentialsProvider = credentialSourceCredentialProvider(credentialSource);
return stsCredentialsProviderFactory().create(credentialsProvider, profile);
}
private AwsCredentialsProvider credentialSourceCredentialProvider(CredentialSourceType credentialSource) {
switch (credentialSource) {
case ECS_CONTAINER:
return ContainerCredentialsProvider.builder().build();
case EC2_INSTANCE_METADATA:
// The IMDS credentials provider should source the endpoint config properties from the currently active profile
Ec2MetadataConfigProvider configProvider = Ec2MetadataConfigProvider.builder()
.profileFile(() -> profileFile)
.profileName(name)
.build();
return InstanceProfileCredentialsProvider.builder()
.endpoint(configProvider.getEndpoint())
.build();
case ENVIRONMENT:
return AwsCredentialsProviderChain.builder()
.addCredentialsProvider(SystemPropertyCredentialsProvider.create())
.addCredentialsProvider(EnvironmentVariableCredentialsProvider.create())
.build();
default:
throw noSourceCredentialsException();
}
}
/**
* Require that the provided properties are configured in this profile.
*/
private void requireProperties(String... requiredProperties) {
Arrays.stream(requiredProperties)
.forEach(p -> Validate.isTrue(properties.containsKey(p),
"Profile property '%s' was not configured for '%s'.", p, name));
}
private IllegalStateException noSourceCredentialsException() {
String error = String.format("The source profile of '%s' was configured to be '%s', but that source profile has no "
+ "credentials configured.", name, properties.get(ProfileProperty.SOURCE_PROFILE));
return new IllegalStateException(error);
}
/**
* Load the factory that can be used to create the STS credentials provider, assuming it is on the classpath.
*/
private ChildProfileCredentialsProviderFactory stsCredentialsProviderFactory() {
try {
Class<?> stsCredentialsProviderFactory = ClassLoaderHelper.loadClass(STS_PROFILE_CREDENTIALS_PROVIDER_FACTORY,
getClass());
return (ChildProfileCredentialsProviderFactory) stsCredentialsProviderFactory.getConstructor().newInstance();
} catch (ClassNotFoundException e) {
throw new IllegalStateException("To use assumed roles in the '" + name + "' profile, the 'sts' service module must "
+ "be on the class path.", e);
} catch (NoSuchMethodException | InvocationTargetException | InstantiationException | IllegalAccessException e) {
throw new IllegalStateException("Failed to create the '" + name + "' profile credentials provider.", e);
}
}
/**
* Load the factory that can be used to create the SSO credentials provider, assuming it is on the classpath.
*/
private ProfileCredentialsProviderFactory ssoCredentialsProviderFactory() {
try {
Class<?> ssoProfileCredentialsProviderFactory = ClassLoaderHelper.loadClass(SSO_PROFILE_CREDENTIALS_PROVIDER_FACTORY,
getClass());
return (ProfileCredentialsProviderFactory) ssoProfileCredentialsProviderFactory.getConstructor().newInstance();
} catch (ClassNotFoundException e) {
throw new IllegalStateException("To use Sso related properties in the '" + name + "' profile, the 'sso' service "
+ "module must be on the class path.", e);
} catch (NoSuchMethodException | InvocationTargetException | InstantiationException | IllegalAccessException e) {
throw new IllegalStateException("Failed to create the '" + name + "' profile credentials provider.", e);
}
}
}
| 1,768 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/credentials | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/credentials/internal/StaticResourcesEndpointProvider.java | /*
* 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.auth.credentials.internal;
import java.io.IOException;
import java.net.URI;
import java.util.Collections;
import java.util.Map;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.regions.util.ResourcesEndpointProvider;
import software.amazon.awssdk.utils.Validate;
@SdkInternalApi
public final class StaticResourcesEndpointProvider implements ResourcesEndpointProvider {
private final URI endpoint;
private final Map<String, String> headers;
public StaticResourcesEndpointProvider(URI endpoint,
Map<String, String> additionalHeaders) {
this.endpoint = Validate.paramNotNull(endpoint, "endpoint");
this.headers = ResourcesEndpointProvider.super.headers();
if (additionalHeaders != null) {
this.headers.putAll(additionalHeaders);
}
}
@Override
public URI endpoint() throws IOException {
return endpoint;
}
@Override
public Map<String, String> headers() {
return Collections.unmodifiableMap(headers);
}
}
| 1,769 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/credentials | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/credentials/internal/WebIdentityTokenCredentialProperties.java | /*
* 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.auth.credentials.internal;
import java.nio.file.Path;
import java.time.Duration;
import software.amazon.awssdk.annotations.SdkProtectedApi;
/**
* A container for credential properties.
*/
@SdkProtectedApi
public class WebIdentityTokenCredentialProperties {
private final String roleArn;
private final String roleSessionName;
private final Path webIdentityTokenFile;
private final Boolean asyncCredentialUpdateEnabled;
private final Duration prefetchTime;
private final Duration staleTime;
private final Duration roleSessionDuration;
private WebIdentityTokenCredentialProperties(Builder builder) {
this.roleArn = builder.roleArn;
this.roleSessionName = builder.roleSessionName;
this.webIdentityTokenFile = builder.webIdentityTokenFile;
this.asyncCredentialUpdateEnabled = builder.asyncCredentialUpdateEnabled;
this.prefetchTime = builder.prefetchTime;
this.staleTime = builder.staleTime;
this.roleSessionDuration = builder.roleSessionDuration;
}
public String roleArn() {
return roleArn;
}
public String roleSessionName() {
return roleSessionName;
}
public Path webIdentityTokenFile() {
return webIdentityTokenFile;
}
public Boolean asyncCredentialUpdateEnabled() {
return asyncCredentialUpdateEnabled;
}
public Duration prefetchTime() {
return prefetchTime;
}
public Duration staleTime() {
return staleTime;
}
public Duration roleSessionDuration() {
return this.roleSessionDuration;
}
public static Builder builder() {
return new Builder();
}
public static final class Builder {
private String roleArn;
private String roleSessionName;
private Path webIdentityTokenFile;
private Boolean asyncCredentialUpdateEnabled;
private Duration prefetchTime;
private Duration staleTime;
private Duration roleSessionDuration;
public Builder roleArn(String roleArn) {
this.roleArn = roleArn;
return this;
}
public Builder roleSessionName(String roleSessionName) {
this.roleSessionName = roleSessionName;
return this;
}
public Builder webIdentityTokenFile(Path webIdentityTokenFile) {
this.webIdentityTokenFile = webIdentityTokenFile;
return this;
}
public Builder asyncCredentialUpdateEnabled(Boolean asyncCredentialUpdateEnabled) {
this.asyncCredentialUpdateEnabled = asyncCredentialUpdateEnabled;
return this;
}
public Builder prefetchTime(Duration prefetchTime) {
this.prefetchTime = prefetchTime;
return this;
}
public Builder staleTime(Duration staleTime) {
this.staleTime = staleTime;
return this;
}
public Builder roleSessionDuration(Duration roleSessionDuration) {
this.roleSessionDuration = roleSessionDuration;
return this;
}
public WebIdentityTokenCredentialProperties build() {
return new WebIdentityTokenCredentialProperties(this);
}
}
}
| 1,770 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/credentials | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/credentials/internal/LazyAwsCredentialsProvider.java | /*
* 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.auth.credentials.internal;
import java.util.function.Supplier;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.auth.credentials.AwsCredentials;
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
import software.amazon.awssdk.utils.IoUtils;
import software.amazon.awssdk.utils.Lazy;
import software.amazon.awssdk.utils.SdkAutoCloseable;
import software.amazon.awssdk.utils.ToString;
/**
* A wrapper for {@link AwsCredentialsProvider} that defers creation of the underlying provider until the first time the
* {@link AwsCredentialsProvider#resolveCredentials()} method is invoked.
*/
@SdkInternalApi
public class LazyAwsCredentialsProvider implements AwsCredentialsProvider, SdkAutoCloseable {
private final Lazy<AwsCredentialsProvider> delegate;
private LazyAwsCredentialsProvider(Supplier<AwsCredentialsProvider> delegateConstructor) {
this.delegate = new Lazy<>(delegateConstructor);
}
public static LazyAwsCredentialsProvider create(Supplier<AwsCredentialsProvider> delegateConstructor) {
return new LazyAwsCredentialsProvider(delegateConstructor);
}
@Override
public AwsCredentials resolveCredentials() {
return delegate.getValue().resolveCredentials();
}
@Override
public void close() {
IoUtils.closeIfCloseable(delegate, null);
}
@Override
public String toString() {
return ToString.builder("LazyAwsCredentialsProvider")
.add("delegate", delegate)
.build();
}
}
| 1,771 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/credentials | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/credentials/internal/WebIdentityCredentialsUtils.java | /*
* 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.auth.credentials.internal;
import java.lang.reflect.InvocationTargetException;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.auth.credentials.WebIdentityTokenCredentialsProviderFactory;
import software.amazon.awssdk.core.internal.util.ClassLoaderHelper;
import software.amazon.awssdk.utils.Logger;
/**
* Utility class used to configure credential providers based on JWT web identity tokens.
*/
@SdkInternalApi
public final class WebIdentityCredentialsUtils {
private static final Logger log = Logger.loggerFor(WebIdentityCredentialsUtils.class);
private static final String STS_WEB_IDENTITY_CREDENTIALS_PROVIDER_FACTORY =
"software.amazon.awssdk.services.sts.internal.StsWebIdentityCredentialsProviderFactory";
private WebIdentityCredentialsUtils() {
}
/**
* Resolves the StsWebIdentityCredentialsProviderFactory from the Sts module if on the classpath to allow
* JWT web identity tokens to be used as credentials.
*
* @return WebIdentityTokenCredentialsProviderFactory
*/
public static WebIdentityTokenCredentialsProviderFactory factory() {
try {
Class<?> stsCredentialsProviderFactory = ClassLoaderHelper.loadClass(STS_WEB_IDENTITY_CREDENTIALS_PROVIDER_FACTORY,
WebIdentityCredentialsUtils.class);
return (WebIdentityTokenCredentialsProviderFactory) stsCredentialsProviderFactory.getConstructor().newInstance();
} catch (ClassNotFoundException e) {
String message = "To use web identity tokens, the 'sts' service module must be on the class path.";
log.warn(() -> message);
throw new IllegalStateException(message, e);
} catch (NoSuchMethodException | InvocationTargetException | InstantiationException | IllegalAccessException e) {
throw new IllegalStateException("Failed to create a web identity token credentials provider.", e);
}
}
}
| 1,772 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/credentials | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/credentials/internal/ContainerCredentialsRetryPolicy.java | /*
* 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.auth.credentials.internal;
import java.io.IOException;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.http.HttpStatusFamily;
import software.amazon.awssdk.regions.util.ResourcesEndpointRetryParameters;
import software.amazon.awssdk.regions.util.ResourcesEndpointRetryPolicy;
@SdkInternalApi
public final class ContainerCredentialsRetryPolicy implements ResourcesEndpointRetryPolicy {
/** Max number of times a request is retried before failing. */
private static final int MAX_RETRIES = 5;
@Override
public boolean shouldRetry(int retriesAttempted, ResourcesEndpointRetryParameters retryParams) {
if (retriesAttempted >= MAX_RETRIES) {
return false;
}
Integer statusCode = retryParams.getStatusCode();
if (statusCode != null && HttpStatusFamily.of(statusCode) == HttpStatusFamily.SERVER_ERROR) {
return true;
}
return retryParams.getException() instanceof IOException;
}
}
| 1,773 |
0 | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/credentials | Create_ds/aws-sdk-java-v2/core/auth/src/main/java/software/amazon/awssdk/auth/credentials/internal/CredentialSourceType.java | /*
* 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.auth.credentials.internal;
import software.amazon.awssdk.annotations.SdkInternalApi;
@SdkInternalApi
public enum CredentialSourceType {
EC2_INSTANCE_METADATA,
ECS_CONTAINER,
ENVIRONMENT;
public static CredentialSourceType parse(String value) {
if (value.equalsIgnoreCase("Ec2InstanceMetadata")) {
return EC2_INSTANCE_METADATA;
} else if (value.equalsIgnoreCase("EcsContainer")) {
return ECS_CONTAINER;
} else if (value.equalsIgnoreCase("Environment")) {
return ENVIRONMENT;
}
throw new IllegalArgumentException(String.format("%s is not a valid credential_source", value));
}
}
| 1,774 |
0 | Create_ds/aws-sdk-java-v2/core/json-utils/src/test/java/software/amazon/awssdk/protocols | Create_ds/aws-sdk-java-v2/core/json-utils/src/test/java/software/amazon/awssdk/protocols/jsoncore/JsonNodeTest.java | package software.amazon.awssdk.protocols.jsoncore;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.utils.StringInputStream;
public class JsonNodeTest {
private static final JsonNodeParser PARSER = JsonNode.parser();
@Test
public void parseString_works() {
assertThat(PARSER.parse("{}").isObject()).isTrue();
}
@Test
public void parseInputStream_works() {
assertThat(PARSER.parse(new StringInputStream("{}")).isObject()).isTrue();
}
@Test
public void parseByteArray_works() {
assertThat(PARSER.parse("{}".getBytes(UTF_8)).isObject()).isTrue();
}
@Test
public void parseNull_givesCorrectType() {
JsonNode node = PARSER.parse("null");
assertThat(node.isNull()).isTrue();
assertThat(node.isBoolean()).isFalse();
assertThat(node.isNumber()).isFalse();
assertThat(node.isString()).isFalse();
assertThat(node.isArray()).isFalse();
assertThat(node.isObject()).isFalse();
assertThat(node.isEmbeddedObject()).isFalse();
assertThatThrownBy(node::asBoolean).isInstanceOf(UnsupportedOperationException.class);
assertThatThrownBy(node::asNumber).isInstanceOf(UnsupportedOperationException.class);
assertThatThrownBy(node::asString).isInstanceOf(UnsupportedOperationException.class);
assertThatThrownBy(node::asArray).isInstanceOf(UnsupportedOperationException.class);
assertThatThrownBy(node::asObject).isInstanceOf(UnsupportedOperationException.class);
assertThatThrownBy(node::asEmbeddedObject).isInstanceOf(UnsupportedOperationException.class);
}
@Test
public void parseBoolean_givesCorrectType() {
String[] options = { "true", "false" };
for (String option : options) {
JsonNode node = PARSER.parse(option);
assertThat(node.isNull()).isFalse();
assertThat(node.isBoolean()).isTrue();
assertThat(node.isNumber()).isFalse();
assertThat(node.isString()).isFalse();
assertThat(node.isArray()).isFalse();
assertThat(node.isObject()).isFalse();
assertThat(node.isEmbeddedObject()).isFalse();
assertThatThrownBy(node::asNumber).isInstanceOf(UnsupportedOperationException.class);
assertThatThrownBy(node::asString).isInstanceOf(UnsupportedOperationException.class);
assertThatThrownBy(node::asArray).isInstanceOf(UnsupportedOperationException.class);
assertThatThrownBy(node::asObject).isInstanceOf(UnsupportedOperationException.class);
assertThatThrownBy(node::asEmbeddedObject).isInstanceOf(UnsupportedOperationException.class);
}
}
@Test
public void parseNumber_givesCorrectType() {
String[] options = { "-1e100", "-1", "0", "1", "1e100" };
for (String option : options) {
JsonNode node = PARSER.parse(option);
assertThat(node.isNull()).isFalse();
assertThat(node.isBoolean()).isFalse();
assertThat(node.isNumber()).isTrue();
assertThat(node.isString()).isFalse();
assertThat(node.isArray()).isFalse();
assertThat(node.isObject()).isFalse();
assertThat(node.isEmbeddedObject()).isFalse();
assertThatThrownBy(node::asBoolean).isInstanceOf(UnsupportedOperationException.class);
assertThatThrownBy(node::asString).isInstanceOf(UnsupportedOperationException.class);
assertThatThrownBy(node::asArray).isInstanceOf(UnsupportedOperationException.class);
assertThatThrownBy(node::asObject).isInstanceOf(UnsupportedOperationException.class);
assertThatThrownBy(node::asEmbeddedObject).isInstanceOf(UnsupportedOperationException.class);
}
}
@Test
public void parseString_givesCorrectType() {
String[] options = { "\"\"", "\"foo\"" };
for (String option : options) {
JsonNode node = PARSER.parse(option);
assertThat(node.isNull()).isFalse();
assertThat(node.isBoolean()).isFalse();
assertThat(node.isNumber()).isFalse();
assertThat(node.isString()).isTrue();
assertThat(node.isArray()).isFalse();
assertThat(node.isObject()).isFalse();
assertThat(node.isEmbeddedObject()).isFalse();
assertThatThrownBy(node::asBoolean).isInstanceOf(UnsupportedOperationException.class);
assertThatThrownBy(node::asNumber).isInstanceOf(UnsupportedOperationException.class);
assertThatThrownBy(node::asArray).isInstanceOf(UnsupportedOperationException.class);
assertThatThrownBy(node::asObject).isInstanceOf(UnsupportedOperationException.class);
assertThatThrownBy(node::asEmbeddedObject).isInstanceOf(UnsupportedOperationException.class);
}
}
@Test
public void parseArray_givesCorrectType() {
String[] options = { "[]", "[null]" };
for (String option : options) {
JsonNode node = PARSER.parse(option);
assertThat(node.isNull()).isFalse();
assertThat(node.isBoolean()).isFalse();
assertThat(node.isNumber()).isFalse();
assertThat(node.isString()).isFalse();
assertThat(node.isArray()).isTrue();
assertThat(node.isObject()).isFalse();
assertThat(node.isEmbeddedObject()).isFalse();
assertThatThrownBy(node::asBoolean).isInstanceOf(UnsupportedOperationException.class);
assertThatThrownBy(node::asNumber).isInstanceOf(UnsupportedOperationException.class);
assertThatThrownBy(node::asString).isInstanceOf(UnsupportedOperationException.class);
assertThatThrownBy(node::asObject).isInstanceOf(UnsupportedOperationException.class);
assertThatThrownBy(node::asEmbeddedObject).isInstanceOf(UnsupportedOperationException.class);
}
}
@Test
public void parseObject_givesCorrectType() {
String[] options = { "{}", "{ \"foo\": null }" };
for (String option : options) {
JsonNode node = PARSER.parse(option);
assertThat(node.isNull()).isFalse();
assertThat(node.isBoolean()).isFalse();
assertThat(node.isNumber()).isFalse();
assertThat(node.isString()).isFalse();
assertThat(node.isArray()).isFalse();
assertThat(node.isObject()).isTrue();
assertThat(node.isEmbeddedObject()).isFalse();
assertThatThrownBy(node::asBoolean).isInstanceOf(UnsupportedOperationException.class);
assertThatThrownBy(node::asNumber).isInstanceOf(UnsupportedOperationException.class);
assertThatThrownBy(node::asString).isInstanceOf(UnsupportedOperationException.class);
assertThatThrownBy(node::asArray).isInstanceOf(UnsupportedOperationException.class);
assertThatThrownBy(node::asEmbeddedObject).isInstanceOf(UnsupportedOperationException.class);
}
}
@Test
public void parseBoolean_givesCorrectValue() {
assertThat(PARSER.parse("true").asBoolean()).isTrue();
assertThat(PARSER.parse("false").asBoolean()).isFalse();
}
@Test
public void parseNumber_givesCorrectValue() {
assertThat(PARSER.parse("0").asNumber()).isEqualTo("0");
assertThat(PARSER.parse("-1").asNumber()).isEqualTo("-1");
assertThat(PARSER.parse("1").asNumber()).isEqualTo("1");
assertThat(PARSER.parse("1e10000").asNumber()).isEqualTo("1e10000");
assertThat(PARSER.parse("-1e10000").asNumber()).isEqualTo("-1e10000");
assertThat(PARSER.parse("1.23").asNumber()).isEqualTo("1.23");
assertThat(PARSER.parse("-1.23").asNumber()).isEqualTo("-1.23");
}
@Test
public void parseString_givesCorrectValue() {
assertThat(PARSER.parse("\"foo\"").asString()).isEqualTo("foo");
assertThat(PARSER.parse("\"\"").asString()).isEqualTo("");
assertThat(PARSER.parse("\" \"").asString()).isEqualTo(" ");
assertThat(PARSER.parse("\"%20\"").asString()).isEqualTo("%20");
assertThat(PARSER.parse("\"\\\"\"").asString()).isEqualTo("\"");
assertThat(PARSER.parse("\" \"").asString()).isEqualTo(" ");
}
@Test
public void parseArray_givesCorrectValue() {
assertThat(PARSER.parse("[]").asArray()).isEmpty();
assertThat(PARSER.parse("[null, 1]").asArray()).satisfies(list -> {
assertThat(list).hasSize(2);
assertThat(list.get(0).isNull()).isTrue();
assertThat(list.get(1).asNumber()).isEqualTo("1");
});
}
@Test
public void parseObject_givesCorrectValue() {
assertThat(PARSER.parse("{}").asObject()).isEmpty();
assertThat(PARSER.parse("{\"foo\": \"bar\", \"baz\": 0}").asObject()).satisfies(map -> {
assertThat(map).hasSize(2);
assertThat(map.get("foo").asString()).isEqualTo("bar");
assertThat(map.get("baz").asNumber()).isEqualTo("0");
});
}
@Test
public void text_returnsContent() {
assertThat(PARSER.parse("null").text()).isEqualTo(null);
assertThat(PARSER.parse("0").text()).isEqualTo("0");
assertThat(PARSER.parse("\"foo\"").text()).isEqualTo("foo");
assertThat(PARSER.parse("true").text()).isEqualTo("true");
assertThat(PARSER.parse("[]").text()).isEqualTo(null);
assertThat(PARSER.parse("{}").text()).isEqualTo(null);
}
@Test
public void getString_returnsContent() {
assertThat(PARSER.parse("null").field("")).isEmpty();
assertThat(PARSER.parse("0").field("")).isEmpty();
assertThat(PARSER.parse("\"foo\"").field("")).isEmpty();
assertThat(PARSER.parse("true").field("")).isEmpty();
assertThat(PARSER.parse("[]").field("")).isEmpty();
assertThat(PARSER.parse("{\"\":0}").field("")).map(JsonNode::asNumber).hasValue("0");
}
@Test
public void getArray_returnsContent() {
assertThat(PARSER.parse("null").index(0)).isEmpty();
assertThat(PARSER.parse("0").index(0)).isEmpty();
assertThat(PARSER.parse("\"foo\"").index(0)).isEmpty();
assertThat(PARSER.parse("true").index(0)).isEmpty();
assertThat(PARSER.parse("[]").index(0)).isEmpty();
assertThat(PARSER.parse("[null]").index(0)).map(JsonNode::isNull).hasValue(true);
assertThat(PARSER.parse("{}").field("")).isEmpty();
}
@Test
public void toStringIsCorrect() {
String input = "{"
+ "\"1\": \"2\","
+ "\"3\": 4,"
+ "\"5\": null,"
+ "\"6\": false,"
+ "\"7\": [[{}]],"
+ "\"8\": \"\\\\n\\\"\""
+ "}";
assertThat(PARSER.parse(input).toString()).isEqualTo(input);
}
@Test
public void exceptionsIncludeErrorLocation() {
assertThatThrownBy(() -> PARSER.parse("{{foo}")).hasMessageContaining("foo");
}
@Test
public void removeErrorLocations_removesErrorLocations() {
assertThatThrownBy(() -> JsonNode.parserBuilder()
.removeErrorLocations(true)
.build()
.parse("{{foo}"))
.satisfies(exception -> {
Throwable cause = exception;
while (cause != null) {
assertThat(cause.getMessage()).doesNotContain("foo");
cause = cause.getCause();
}
});
}
} | 1,775 |
0 | Create_ds/aws-sdk-java-v2/core/json-utils/src/main/java/software/amazon/awssdk/protocols | Create_ds/aws-sdk-java-v2/core/json-utils/src/main/java/software/amazon/awssdk/protocols/jsoncore/JsonNode.java | /*
* 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.protocols.jsoncore;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.protocols.jsoncore.internal.ObjectJsonNode;
import software.amazon.awssdk.thirdparty.jackson.core.JsonFactory;
/**
* A node in a JSON document. Either a number, string, boolean, array, object or null. Also can be an embedded object,
* which is a non-standard type used in JSON extensions, like CBOR.
*
* <p>Created from a JSON document via {@link #parser()} or {@link #parserBuilder()}.
*
* <p>The type of node can be determined using "is" methods like {@link #isNumber()} and {@link #isString()}.
* Once the type is determined, the value of the node can be extracted via the "as" methods, like {@link #asNumber()}
* and {@link #asString()}.
*/
@SdkProtectedApi
public interface JsonNode {
/**
* Create a {@link JsonNodeParser} for generating a {@link JsonNode} from a JSON document.
*/
static JsonNodeParser parser() {
return JsonNodeParser.create();
}
/**
* Create a {@link JsonNodeParser.Builder} for generating a {@link JsonNode} from a JSON document.
*/
static JsonNodeParser.Builder parserBuilder() {
return JsonNodeParser.builder();
}
/**
* Return an empty object node.
*/
static JsonNode emptyObjectNode() {
return new ObjectJsonNode(Collections.emptyMap());
}
/**
* Returns true if this node represents a JSON number: https://datatracker.ietf.org/doc/html/rfc8259#section-6
*
* @see #asNumber()
*/
default boolean isNumber() {
return false;
}
/**
* Returns true if this node represents a JSON string: https://datatracker.ietf.org/doc/html/rfc8259#section-7
*
* @see #asString()
*/
default boolean isString() {
return false;
}
/**
* Returns true if this node represents a JSON boolean: https://datatracker.ietf.org/doc/html/rfc8259#section-3
*
* @see #asBoolean()
*/
default boolean isBoolean() {
return false;
}
/**
* Returns true if this node represents a JSON null: https://datatracker.ietf.org/doc/html/rfc8259#section-3
*/
default boolean isNull() {
return false;
}
/**
* Returns true if this node represents a JSON array: https://datatracker.ietf.org/doc/html/rfc8259#section-5
*
* @see #asArray()
*/
default boolean isArray() {
return false;
}
/**
* Returns true if this node represents a JSON object: https://datatracker.ietf.org/doc/html/rfc8259#section-4
*
* @see #asObject()
*/
default boolean isObject() {
return false;
}
/**
* Returns true if this node represents a JSON "embedded object". This non-standard type is associated with JSON extensions,
* like CBOR or ION. It allows additional data types to be embedded in a JSON document, like a timestamp or a raw byte array.
*
* <p>Users who are only concerned with handling JSON can ignore this field. It will only be present when using a custom
* {@link JsonFactory} via {@link JsonNodeParser.Builder#jsonFactory(JsonFactory)}.
*
* @see #asEmbeddedObject()
*/
default boolean isEmbeddedObject() {
return false;
}
/**
* When {@link #isNumber()} is true, this returns the number associated with this node. This will throw an exception if
* {@link #isNumber()} is false.
*
* @see #text()
*/
String asNumber();
/**
* When {@link #isString()}, is true, this returns the string associated with this node. This will throw an exception if
* {@link #isString()} ()} is false.
*/
String asString();
/**
* When {@link #isBoolean()} is true, this returns the boolean associated with this node. This will throw an exception if
* {@link #isBoolean()} is false.
*/
boolean asBoolean();
/**
* When {@link #isArray()} is true, this returns the array associated with this node. This will throw an exception if
* {@link #isArray()} is false.
*/
List<JsonNode> asArray();
/**
* When {@link #isObject()} is true, this returns the object associated with this node. This will throw an exception if
* {@link #isObject()} is false.
*/
Map<String, JsonNode> asObject();
/**
* When {@link #isEmbeddedObject()} is true, this returns the embedded object associated with this node. This will throw
* an exception if {@link #isEmbeddedObject()} is false.
*
* @see #isEmbeddedObject()
*/
Object asEmbeddedObject();
/**
* Visit this node using the provided visitor.
*/
<T> T visit(JsonNodeVisitor<T> visitor);
/**
* When {@link #isString()}, {@link #isBoolean()}, or {@link #isNumber()} is true, this will return the value of this node
* as a textual string. If this is any other type, this will return null.
*/
String text();
/**
* When {@link #isObject()} is true, this will return the result of {@code Optional.ofNullable(asObject().get(child))}. If
* this is any other type, this will return {@link Optional#empty()}.
*/
default Optional<JsonNode> field(String child) {
return Optional.empty();
}
/**
* When {@link #isArray()} is true, this will return the result of {@code asArray().get(child)} if child is within bounds. If
* this is any other type or the child is out of bounds, this will return {@link Optional#empty()}.
*/
default Optional<JsonNode> index(int child) {
return Optional.empty();
}
}
| 1,776 |
0 | Create_ds/aws-sdk-java-v2/core/json-utils/src/main/java/software/amazon/awssdk/protocols | Create_ds/aws-sdk-java-v2/core/json-utils/src/main/java/software/amazon/awssdk/protocols/jsoncore/JsonNodeVisitor.java | /*
* 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.protocols.jsoncore;
import java.util.List;
import java.util.Map;
import software.amazon.awssdk.annotations.SdkProtectedApi;
/**
* Converter from a {@link JsonNode} to a new type. This is usually invoked via {@link JsonNode#visit(JsonNodeVisitor)}.
*/
@SdkProtectedApi
public interface JsonNodeVisitor<T> {
/**
* Invoked if {@link JsonNode#visit(JsonNodeVisitor)} is invoked on a null JSON node.
*/
T visitNull();
/**
* Invoked if {@link JsonNode#visit(JsonNodeVisitor)} is invoked on a boolean JSON node.
*/
T visitBoolean(boolean bool);
/**
* Invoked if {@link JsonNode#visit(JsonNodeVisitor)} is invoked on a number JSON node.
*/
T visitNumber(String number);
/**
* Invoked if {@link JsonNode#visit(JsonNodeVisitor)} is invoked on a string JSON node.
*/
T visitString(String string);
/**
* Invoked if {@link JsonNode#visit(JsonNodeVisitor)} is invoked on an array JSON node.
*/
T visitArray(List<JsonNode> array);
/**
* Invoked if {@link JsonNode#visit(JsonNodeVisitor)} is invoked on an object JSON node.
*/
T visitObject(Map<String, JsonNode> object);
/**
* Invoked if {@link JsonNode#visit(JsonNodeVisitor)} is invoked on an embedded object JSON node.
*/
T visitEmbeddedObject(Object embeddedObject);
}
| 1,777 |
0 | Create_ds/aws-sdk-java-v2/core/json-utils/src/main/java/software/amazon/awssdk/protocols | Create_ds/aws-sdk-java-v2/core/json-utils/src/main/java/software/amazon/awssdk/protocols/jsoncore/JsonNodeParser.java | /*
* 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.protocols.jsoncore;
import static software.amazon.awssdk.utils.FunctionalUtils.invokeSafely;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.protocols.jsoncore.internal.ArrayJsonNode;
import software.amazon.awssdk.protocols.jsoncore.internal.BooleanJsonNode;
import software.amazon.awssdk.protocols.jsoncore.internal.EmbeddedObjectJsonNode;
import software.amazon.awssdk.protocols.jsoncore.internal.NullJsonNode;
import software.amazon.awssdk.protocols.jsoncore.internal.NumberJsonNode;
import software.amazon.awssdk.protocols.jsoncore.internal.ObjectJsonNode;
import software.amazon.awssdk.protocols.jsoncore.internal.StringJsonNode;
import software.amazon.awssdk.thirdparty.jackson.core.JsonFactory;
import software.amazon.awssdk.thirdparty.jackson.core.JsonParseException;
import software.amazon.awssdk.thirdparty.jackson.core.JsonParser;
import software.amazon.awssdk.thirdparty.jackson.core.JsonToken;
import software.amazon.awssdk.thirdparty.jackson.core.json.JsonReadFeature;
/**
* Parses an JSON document into a simple DOM-like structure, {@link JsonNode}.
*
* <p>This is created using {@link #create()} or {@link #builder()}.
*/
@SdkProtectedApi
public final class JsonNodeParser {
/**
* The default {@link JsonFactory} used for {@link #create()} or if a factory is not configured via
* {@link Builder#jsonFactory(JsonFactory)}.
*/
public static final JsonFactory DEFAULT_JSON_FACTORY =
JsonFactory.builder()
.configure(JsonReadFeature.ALLOW_JAVA_COMMENTS, true)
.build();
private final boolean removeErrorLocations;
private final JsonFactory jsonFactory;
private JsonNodeParser(Builder builder) {
this.removeErrorLocations = builder.removeErrorLocations;
this.jsonFactory = builder.jsonFactory;
}
/**
* Create a parser using the default configuration.
*/
public static JsonNodeParser create() {
return builder().build();
}
/**
* Create a parser using custom configuration.
*/
public static JsonNodeParser.Builder builder() {
return new Builder();
}
/**
* Parse the provided {@link InputStream} into a {@link JsonNode}.
*/
public JsonNode parse(InputStream content) {
return invokeSafely(() -> {
try (JsonParser parser = jsonFactory.createParser(content)
.configure(JsonParser.Feature.AUTO_CLOSE_SOURCE, false)) {
return parse(parser);
}
});
}
/**
* Parse the provided {@code byte[]} into a {@link JsonNode}.
*/
public JsonNode parse(byte[] content) {
return invokeSafely(() -> {
try (JsonParser parser = jsonFactory.createParser(content)
.configure(JsonParser.Feature.AUTO_CLOSE_SOURCE, false)) {
return parse(parser);
}
});
}
/**
* Parse the provided {@link String} into a {@link JsonNode}.
*/
public JsonNode parse(String content) {
return invokeSafely(() -> {
try (JsonParser parser = jsonFactory.createParser(content)
.configure(JsonParser.Feature.AUTO_CLOSE_SOURCE, false)) {
return parse(parser);
}
});
}
private JsonNode parse(JsonParser parser) throws IOException {
try {
return parseToken(parser, parser.nextToken());
} catch (Exception e) {
removeErrorLocationsIfRequired(e);
throw e;
}
}
private void removeErrorLocationsIfRequired(Throwable exception) {
if (removeErrorLocations) {
removeErrorLocations(exception);
}
}
private void removeErrorLocations(Throwable exception) {
if (exception == null) {
return;
}
if (exception instanceof JsonParseException) {
((JsonParseException) exception).clearLocation();
}
removeErrorLocations(exception.getCause());
}
private JsonNode parseToken(JsonParser parser, JsonToken token) throws IOException {
if (token == null) {
return null;
}
switch (token) {
case VALUE_STRING:
return new StringJsonNode(parser.getText());
case VALUE_FALSE:
return new BooleanJsonNode(false);
case VALUE_TRUE:
return new BooleanJsonNode(true);
case VALUE_NULL:
return NullJsonNode.instance();
case VALUE_NUMBER_FLOAT:
case VALUE_NUMBER_INT:
return new NumberJsonNode(parser.getText());
case START_OBJECT:
return parseObject(parser);
case START_ARRAY:
return parseArray(parser);
case VALUE_EMBEDDED_OBJECT:
return new EmbeddedObjectJsonNode(parser.getEmbeddedObject());
default:
throw new IllegalArgumentException("Unexpected JSON token - " + token);
}
}
private JsonNode parseObject(JsonParser parser) throws IOException {
JsonToken currentToken = parser.nextToken();
Map<String, JsonNode> object = new LinkedHashMap<>();
while (currentToken != JsonToken.END_OBJECT) {
String fieldName = parser.getText();
object.put(fieldName, parseToken(parser, parser.nextToken()));
currentToken = parser.nextToken();
}
return new ObjectJsonNode(object);
}
private JsonNode parseArray(JsonParser parser) throws IOException {
JsonToken currentToken = parser.nextToken();
List<JsonNode> array = new ArrayList<>();
while (currentToken != JsonToken.END_ARRAY) {
array.add(parseToken(parser, currentToken));
currentToken = parser.nextToken();
}
return new ArrayJsonNode(array);
}
/**
* A builder for configuring and creating {@link JsonNodeParser}. Created via {@link #builder()}.
*/
public static final class Builder {
private JsonFactory jsonFactory = DEFAULT_JSON_FACTORY;
private boolean removeErrorLocations = false;
private Builder() {
}
/**
* Whether error locations should be removed if parsing fails. This prevents the content of the JSON from appearing in
* error messages. This is useful when the content of the JSON may be sensitive and not want to be logged.
*
* <p>By default, this is false.
*/
public Builder removeErrorLocations(boolean removeErrorLocations) {
this.removeErrorLocations = removeErrorLocations;
return this;
}
/**
* The {@link JsonFactory} implementation to be used when parsing the input. This allows JSON extensions like CBOR or
* Ion to be supported.
*
* <p>It's highly recommended us use a shared {@code JsonFactory} where possible, so they should be stored statically:
* http://wiki.fasterxml.com/JacksonBestPracticesPerformance
*
* <p>By default, this is {@link #DEFAULT_JSON_FACTORY}.
*/
public Builder jsonFactory(JsonFactory jsonFactory) {
this.jsonFactory = jsonFactory;
return this;
}
/**
* Build a {@link JsonNodeParser} based on the current configuration of this builder.
*/
public JsonNodeParser build() {
return new JsonNodeParser(this);
}
}
}
| 1,778 |
0 | Create_ds/aws-sdk-java-v2/core/json-utils/src/main/java/software/amazon/awssdk/protocols | Create_ds/aws-sdk-java-v2/core/json-utils/src/main/java/software/amazon/awssdk/protocols/jsoncore/JsonWriter.java | /*
* 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.protocols.jsoncore;
import static software.amazon.awssdk.protocols.jsoncore.JsonNodeParser.DEFAULT_JSON_FACTORY;
import static software.amazon.awssdk.utils.DateUtils.formatUnixTimestampInstant;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.time.Instant;
import software.amazon.awssdk.annotations.SdkProtectedApi;
import software.amazon.awssdk.thirdparty.jackson.core.JsonFactory;
import software.amazon.awssdk.thirdparty.jackson.core.JsonGenerator;
import software.amazon.awssdk.utils.BinaryUtils;
import software.amazon.awssdk.utils.FunctionalUtils;
import software.amazon.awssdk.utils.SdkAutoCloseable;
/**
* Thin wrapper around Jackson's JSON generator.
*/
@SdkProtectedApi
public class JsonWriter implements SdkAutoCloseable {
private static final int DEFAULT_BUFFER_SIZE = 1024;
private final ByteArrayOutputStream baos;
private final JsonGenerator generator;
private JsonWriter(Builder builder) {
JsonGeneratorFactory jsonGeneratorFactory = builder.jsonGeneratorFactory != null
? builder.jsonGeneratorFactory
: DEFAULT_JSON_FACTORY::createGenerator;
try {
baos = new ByteArrayOutputStream(DEFAULT_BUFFER_SIZE);
generator = jsonGeneratorFactory.createGenerator(baos);
} catch (IOException e) {
throw new JsonGenerationException(e);
}
}
public static JsonWriter create() {
return builder().build();
}
public static JsonWriter.Builder builder() {
return new Builder();
}
public JsonWriter writeStartArray() {
return unsafeWrite(generator::writeStartArray);
}
public JsonWriter writeEndArray() {
return unsafeWrite(generator::writeEndArray);
}
public JsonWriter writeNull() {
return unsafeWrite(generator::writeEndArray);
}
public JsonWriter writeStartObject() {
return unsafeWrite(generator::writeStartObject);
}
public JsonWriter writeEndObject() {
return unsafeWrite(generator::writeEndObject);
}
public JsonWriter writeFieldName(String fieldName) {
return unsafeWrite(() -> generator.writeFieldName(fieldName));
}
public JsonWriter writeValue(String val) {
return unsafeWrite(() -> generator.writeString(val));
}
public JsonWriter writeValue(boolean bool) {
return unsafeWrite(() -> generator.writeBoolean(bool));
}
public JsonWriter writeValue(long val) {
return unsafeWrite(() -> generator.writeNumber(val));
}
public JsonWriter writeValue(double val) {
return unsafeWrite(() -> generator.writeNumber(val));
}
public JsonWriter writeValue(float val) {
return unsafeWrite(() -> generator.writeNumber(val));
}
public JsonWriter writeValue(short val) {
return unsafeWrite(() -> generator.writeNumber(val));
}
public JsonWriter writeValue(int val) {
return unsafeWrite(() -> generator.writeNumber(val));
}
public JsonWriter writeValue(ByteBuffer bytes) {
return unsafeWrite(() -> generator.writeBinary(BinaryUtils.copyBytesFrom(bytes)));
}
public JsonWriter writeValue(Instant instant) {
return unsafeWrite(() -> generator.writeNumber(formatUnixTimestampInstant(instant)));
}
public JsonWriter writeValue(BigDecimal value) {
return unsafeWrite(() -> generator.writeString(value.toString()));
}
public JsonWriter writeValue(BigInteger value) {
return unsafeWrite(() -> generator.writeNumber(value));
}
public JsonWriter writeNumber(String number) {
return unsafeWrite(() -> generator.writeNumber(number));
}
/**
* Closes the generator and flushes to write. Must be called when finished writing JSON
* content.
*/
@Override
public void close() {
try {
generator.close();
} catch (IOException e) {
throw new JsonGenerationException(e);
}
}
/**
* Get the JSON content as a UTF-8 encoded byte array. It is recommended to hold onto the array
* reference rather then making repeated calls to this method as a new array will be created
* each time.
*
* @return Array of UTF-8 encoded bytes that make up the generated JSON.
*/
public byte[] getBytes() {
close();
return baos.toByteArray();
}
private JsonWriter unsafeWrite(FunctionalUtils.UnsafeRunnable r) {
try {
r.run();
} catch (Exception e) {
throw new JsonGenerationException(e);
}
return this;
}
/**
* A builder for configuring and creating {@link JsonWriter}. Created via {@link #builder()}.
*/
public static final class Builder {
private JsonGeneratorFactory jsonGeneratorFactory;
private Builder() {
}
/**
* The {@link JsonFactory} implementation to be used when parsing the input. This allows JSON extensions like CBOR or
* Ion to be supported.
*
* <p>It's highly recommended to use a shared {@code JsonFactory} where possible, so they should be stored statically:
* http://wiki.fasterxml.com/JacksonBestPracticesPerformance
*
* <p>By default, this is {@link JsonNodeParser#DEFAULT_JSON_FACTORY}.
*
* <p>Setting this value will also override any values set via {@link #jsonGeneratorFactory}.
*/
public JsonWriter.Builder jsonFactory(JsonFactory jsonFactory) {
jsonGeneratorFactory(jsonFactory::createGenerator);
return this;
}
/**
* A factory for {@link JsonGenerator}s based on an {@link OutputStream}. This allows custom JSON generator
* configuration, like pretty-printing output.
*
* <p>It's highly recommended to use a shared {@code JsonFactory} within this generator factory, where possible, so they
* should be stored statically: http://wiki.fasterxml.com/JacksonBestPracticesPerformance
*
* <p>By default, this delegates to {@link JsonNodeParser#DEFAULT_JSON_FACTORY} to create the generator.
*
* <p>Setting this value will also override any values set via {@link #jsonFactory}.
*/
public JsonWriter.Builder jsonGeneratorFactory(JsonGeneratorFactory jsonGeneratorFactory) {
this.jsonGeneratorFactory = jsonGeneratorFactory;
return this;
}
/**
* Build a {@link JsonNodeParser} based on the current configuration of this builder.
*/
public JsonWriter build() {
return new JsonWriter(this);
}
}
/**
* Generate a {@link JsonGenerator} for a {@link OutputStream}. This will get called once for each "write" call.
*/
@FunctionalInterface
public interface JsonGeneratorFactory {
JsonGenerator createGenerator(OutputStream outputStream) throws IOException;
}
/**
* Indicates an issue writing JSON content.
*/
public static class JsonGenerationException extends RuntimeException {
public JsonGenerationException(Throwable t) {
super(t);
}
}
}
| 1,779 |
0 | Create_ds/aws-sdk-java-v2/core/json-utils/src/main/java/software/amazon/awssdk/protocols/jsoncore | Create_ds/aws-sdk-java-v2/core/json-utils/src/main/java/software/amazon/awssdk/protocols/jsoncore/internal/BooleanJsonNode.java | /*
* 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.protocols.jsoncore.internal;
import java.util.List;
import java.util.Map;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.protocols.jsoncore.JsonNode;
import software.amazon.awssdk.protocols.jsoncore.JsonNodeVisitor;
/**
* A boolean {@link JsonNode}.
*/
@SdkInternalApi
public final class BooleanJsonNode implements JsonNode {
private final boolean value;
public BooleanJsonNode(boolean value) {
this.value = value;
}
@Override
public boolean isBoolean() {
return true;
}
@Override
public String asNumber() {
throw new UnsupportedOperationException("A JSON boolean cannot be converted to a number.");
}
@Override
public String asString() {
throw new UnsupportedOperationException("A JSON boolean cannot be converted to a string.");
}
@Override
public boolean asBoolean() {
return value;
}
@Override
public List<JsonNode> asArray() {
throw new UnsupportedOperationException("A JSON boolean cannot be converted to an array.");
}
@Override
public Map<String, JsonNode> asObject() {
throw new UnsupportedOperationException("A JSON boolean cannot be converted to an object.");
}
@Override
public Object asEmbeddedObject() {
throw new UnsupportedOperationException("A JSON boolean cannot be converted to an embedded object.");
}
@Override
public <T> T visit(JsonNodeVisitor<T> visitor) {
return visitor.visitBoolean(asBoolean());
}
@Override
public String text() {
return Boolean.toString(value);
}
@Override
public String toString() {
return Boolean.toString(value);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
BooleanJsonNode that = (BooleanJsonNode) o;
return value == that.value;
}
@Override
public int hashCode() {
return (value ? 1 : 0);
}
}
| 1,780 |
0 | Create_ds/aws-sdk-java-v2/core/json-utils/src/main/java/software/amazon/awssdk/protocols/jsoncore | Create_ds/aws-sdk-java-v2/core/json-utils/src/main/java/software/amazon/awssdk/protocols/jsoncore/internal/NullJsonNode.java | /*
* 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.protocols.jsoncore.internal;
import java.util.List;
import java.util.Map;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.protocols.jsoncore.JsonNode;
import software.amazon.awssdk.protocols.jsoncore.JsonNodeVisitor;
/**
* A null {@link JsonNode}.
*/
@SdkInternalApi
public final class NullJsonNode implements JsonNode {
private static final NullJsonNode INSTANCE = new NullJsonNode();
private NullJsonNode() {
}
public static NullJsonNode instance() {
return INSTANCE;
}
@Override
public boolean isNull() {
return true;
}
@Override
public String asNumber() {
throw new UnsupportedOperationException("A JSON null cannot be converted to a number.");
}
@Override
public String asString() {
throw new UnsupportedOperationException("A JSON null cannot be converted to a string.");
}
@Override
public boolean asBoolean() {
throw new UnsupportedOperationException("A JSON null cannot be converted to a boolean.");
}
@Override
public List<JsonNode> asArray() {
throw new UnsupportedOperationException("A JSON null cannot be converted to an array.");
}
@Override
public Map<String, JsonNode> asObject() {
throw new UnsupportedOperationException("A JSON null cannot be converted to an object.");
}
@Override
public Object asEmbeddedObject() {
throw new UnsupportedOperationException("A JSON null cannot be converted to an embedded object.");
}
@Override
public <T> T visit(JsonNodeVisitor<T> visitor) {
return visitor.visitNull();
}
@Override
public String text() {
return null;
}
@Override
public String toString() {
return "null";
}
@Override
public boolean equals(Object obj) {
return this == obj;
}
@Override
public int hashCode() {
return 0;
}
}
| 1,781 |
0 | Create_ds/aws-sdk-java-v2/core/json-utils/src/main/java/software/amazon/awssdk/protocols/jsoncore | Create_ds/aws-sdk-java-v2/core/json-utils/src/main/java/software/amazon/awssdk/protocols/jsoncore/internal/ObjectJsonNode.java | /*
* 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.protocols.jsoncore.internal;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.protocols.jsoncore.JsonNode;
import software.amazon.awssdk.protocols.jsoncore.JsonNodeVisitor;
/**
* An object {@link JsonNode}.
*/
@SdkInternalApi
public final class ObjectJsonNode implements JsonNode {
private final Map<String, JsonNode> value;
public ObjectJsonNode(Map<String, JsonNode> value) {
this.value = value;
}
@Override
public boolean isObject() {
return true;
}
@Override
public String asNumber() {
throw new UnsupportedOperationException("A JSON object cannot be converted to a number.");
}
@Override
public String asString() {
throw new UnsupportedOperationException("A JSON object cannot be converted to a string.");
}
@Override
public boolean asBoolean() {
throw new UnsupportedOperationException("A JSON object cannot be converted to a boolean.");
}
@Override
public List<JsonNode> asArray() {
throw new UnsupportedOperationException("A JSON object cannot be converted to an array.");
}
@Override
public Map<String, JsonNode> asObject() {
return value;
}
@Override
public <T> T visit(JsonNodeVisitor<T> visitor) {
return visitor.visitObject(asObject());
}
@Override
public Object asEmbeddedObject() {
throw new UnsupportedOperationException("A JSON object cannot be converted to an embedded object.");
}
@Override
public String text() {
return null;
}
@Override
public Optional<JsonNode> field(String child) {
return Optional.ofNullable(value.get(child));
}
@Override
public String toString() {
if (value.isEmpty()) {
return "{}";
}
StringBuilder output = new StringBuilder();
output.append("{");
value.forEach((k, v) -> output.append("\"").append(k).append("\": ")
.append(v.toString()).append(","));
output.setCharAt(output.length() - 1, '}');
return output.toString();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ObjectJsonNode that = (ObjectJsonNode) o;
return value.equals(that.value);
}
@Override
public int hashCode() {
return value.hashCode();
}
}
| 1,782 |
0 | Create_ds/aws-sdk-java-v2/core/json-utils/src/main/java/software/amazon/awssdk/protocols/jsoncore | Create_ds/aws-sdk-java-v2/core/json-utils/src/main/java/software/amazon/awssdk/protocols/jsoncore/internal/NumberJsonNode.java | /*
* 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.protocols.jsoncore.internal;
import java.util.List;
import java.util.Map;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.protocols.jsoncore.JsonNode;
import software.amazon.awssdk.protocols.jsoncore.JsonNodeVisitor;
/**
* A numeric {@link JsonNode}.
*/
@SdkInternalApi
public final class NumberJsonNode implements JsonNode {
private final String value;
public NumberJsonNode(String value) {
this.value = value;
}
@Override
public boolean isNumber() {
return true;
}
@Override
public String asNumber() {
return value;
}
@Override
public String asString() {
throw new UnsupportedOperationException("A JSON number cannot be converted to a string.");
}
@Override
public boolean asBoolean() {
throw new UnsupportedOperationException("A JSON number cannot be converted to a boolean.");
}
@Override
public List<JsonNode> asArray() {
throw new UnsupportedOperationException("A JSON number cannot be converted to an array.");
}
@Override
public Map<String, JsonNode> asObject() {
throw new UnsupportedOperationException("A JSON number cannot be converted to an object.");
}
@Override
public Object asEmbeddedObject() {
throw new UnsupportedOperationException("A JSON number cannot be converted to an embedded object.");
}
@Override
public <T> T visit(JsonNodeVisitor<T> visitor) {
return visitor.visitNumber(asNumber());
}
@Override
public String text() {
return value;
}
@Override
public String toString() {
return value;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
NumberJsonNode that = (NumberJsonNode) o;
return value.equals(that.value);
}
@Override
public int hashCode() {
return value.hashCode();
}
}
| 1,783 |
0 | Create_ds/aws-sdk-java-v2/core/json-utils/src/main/java/software/amazon/awssdk/protocols/jsoncore | Create_ds/aws-sdk-java-v2/core/json-utils/src/main/java/software/amazon/awssdk/protocols/jsoncore/internal/EmbeddedObjectJsonNode.java | /*
* 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.protocols.jsoncore.internal;
import java.util.List;
import java.util.Map;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.protocols.jsoncore.JsonNode;
import software.amazon.awssdk.protocols.jsoncore.JsonNodeVisitor;
/**
* An embedded object {@link JsonNode}.
*/
@SdkInternalApi
public final class EmbeddedObjectJsonNode implements JsonNode {
private final Object embeddedObject;
public EmbeddedObjectJsonNode(Object embeddedObject) {
this.embeddedObject = embeddedObject;
}
@Override
public boolean isEmbeddedObject() {
return true;
}
@Override
public String asNumber() {
throw new UnsupportedOperationException("A JSON embedded object cannot be converted to a number.");
}
@Override
public String asString() {
throw new UnsupportedOperationException("A JSON embedded object cannot be converted to a string.");
}
@Override
public boolean asBoolean() {
throw new UnsupportedOperationException("A JSON embedded object cannot be converted to a boolean.");
}
@Override
public List<JsonNode> asArray() {
throw new UnsupportedOperationException("A JSON embedded object cannot be converted to an array.");
}
@Override
public Map<String, JsonNode> asObject() {
throw new UnsupportedOperationException("A JSON embedded object cannot be converted to an object.");
}
@Override
public Object asEmbeddedObject() {
return embeddedObject;
}
@Override
public <T> T visit(JsonNodeVisitor<T> visitor) {
return visitor.visitEmbeddedObject(asEmbeddedObject());
}
@Override
public String text() {
return null;
}
@Override
public String toString() {
return "<<Embedded Object (" + embeddedObject.getClass().getSimpleName() + ")>>";
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
EmbeddedObjectJsonNode that = (EmbeddedObjectJsonNode) o;
return embeddedObject.equals(that.embeddedObject);
}
@Override
public int hashCode() {
return embeddedObject.hashCode();
}
}
| 1,784 |
0 | Create_ds/aws-sdk-java-v2/core/json-utils/src/main/java/software/amazon/awssdk/protocols/jsoncore | Create_ds/aws-sdk-java-v2/core/json-utils/src/main/java/software/amazon/awssdk/protocols/jsoncore/internal/StringJsonNode.java | /*
* 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.protocols.jsoncore.internal;
import java.util.List;
import java.util.Map;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.protocols.jsoncore.JsonNode;
import software.amazon.awssdk.protocols.jsoncore.JsonNodeVisitor;
import software.amazon.awssdk.utils.Validate;
/**
* A string {@link JsonNode}.
*/
@SdkInternalApi
public final class StringJsonNode implements JsonNode {
private final String value;
public StringJsonNode(String value) {
Validate.paramNotNull(value, "value");
this.value = value;
}
@Override
public boolean isString() {
return true;
}
@Override
public String asNumber() {
throw new UnsupportedOperationException("A JSON string cannot be converted to a number.");
}
@Override
public String asString() {
return value;
}
@Override
public boolean asBoolean() {
throw new UnsupportedOperationException("A JSON string cannot be converted to a boolean.");
}
@Override
public List<JsonNode> asArray() {
throw new UnsupportedOperationException("A JSON string cannot be converted to an array.");
}
@Override
public Map<String, JsonNode> asObject() {
throw new UnsupportedOperationException("A JSON string cannot be converted to an object.");
}
@Override
public Object asEmbeddedObject() {
throw new UnsupportedOperationException("A JSON string cannot be converted to an embedded object.");
}
@Override
public <T> T visit(JsonNodeVisitor<T> visitor) {
return visitor.visitString(asString());
}
@Override
public String text() {
return value;
}
@Override
public String toString() {
// Does not handle unicode control characters
return "\"" +
value.replace("\\", "\\\\")
.replace("\"", "\\\"")
+ "\"";
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
StringJsonNode that = (StringJsonNode) o;
return value.equals(that.value);
}
@Override
public int hashCode() {
return value.hashCode();
}
} | 1,785 |
0 | Create_ds/aws-sdk-java-v2/core/json-utils/src/main/java/software/amazon/awssdk/protocols/jsoncore | Create_ds/aws-sdk-java-v2/core/json-utils/src/main/java/software/amazon/awssdk/protocols/jsoncore/internal/ArrayJsonNode.java | /*
* 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.protocols.jsoncore.internal;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import software.amazon.awssdk.annotations.SdkInternalApi;
import software.amazon.awssdk.protocols.jsoncore.JsonNode;
import software.amazon.awssdk.protocols.jsoncore.JsonNodeVisitor;
/**
* An array {@link JsonNode}.
*/
@SdkInternalApi
public final class ArrayJsonNode implements JsonNode {
private final List<JsonNode> value;
public ArrayJsonNode(List<JsonNode> value) {
this.value = value;
}
@Override
public boolean isArray() {
return true;
}
@Override
public String asNumber() {
throw new UnsupportedOperationException("A JSON array cannot be converted to a number.");
}
@Override
public String asString() {
throw new UnsupportedOperationException("A JSON array cannot be converted to a string.");
}
@Override
public boolean asBoolean() {
throw new UnsupportedOperationException("A JSON array cannot be converted to a boolean.");
}
@Override
public List<JsonNode> asArray() {
return value;
}
@Override
public Map<String, JsonNode> asObject() {
throw new UnsupportedOperationException("A JSON array cannot be converted to an object.");
}
@Override
public Object asEmbeddedObject() {
throw new UnsupportedOperationException("A JSON array cannot be converted to an embedded object.");
}
@Override
public <T> T visit(JsonNodeVisitor<T> visitor) {
return visitor.visitArray(asArray());
}
@Override
public String text() {
return null;
}
@Override
public Optional<JsonNode> index(int child) {
if (child < 0 || child >= value.size()) {
return Optional.empty();
}
return Optional.of(value.get(child));
}
@Override
public String toString() {
return value.toString();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ArrayJsonNode that = (ArrayJsonNode) o;
return value.equals(that.value);
}
@Override
public int hashCode() {
return value.hashCode();
}
}
| 1,786 |
0 | Create_ds/aws-sdk-java-v2/core/endpoints-spi/src/test/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/core/endpoints-spi/src/test/java/software/amazon/awssdk/endpoints/EndpointTest.java | /*
* 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.endpoints;
import static org.assertj.core.api.Assertions.assertThat;
import java.net.URI;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import nl.jqno.equalsverifier.EqualsVerifier;
import org.junit.jupiter.api.Test;
public class EndpointTest {
private static final EndpointAttributeKey<String> TEST_STRING_ATTR =
new EndpointAttributeKey<>("StringAttr", String.class);
@Test
public void testEqualsHashCode() {
EqualsVerifier.forClass(Endpoint.class)
.verify();
}
@Test
public void build_maximal() {
Endpoint endpoint = Endpoint.builder()
.url(URI.create("https://myservice.aws"))
.putHeader("foo", "bar")
.putHeader("foo", "baz")
.putAttribute(TEST_STRING_ATTR, "baz")
.build();
Map<String, List<String>> expectedHeaders = new HashMap<>();
expectedHeaders.put("foo", Arrays.asList("bar", "baz"));
assertThat(endpoint.url()).isEqualTo(URI.create("https://myservice.aws"));
assertThat(endpoint.headers()).isEqualTo(expectedHeaders);
assertThat(endpoint.attribute(TEST_STRING_ATTR)).isEqualTo("baz");
}
@Test
public void toBuilder_unmodified_equalToOriginal() {
Endpoint original = Endpoint.builder()
.url(URI.create("https://myservice.aws"))
.putHeader("foo", "bar")
.putAttribute(TEST_STRING_ATTR, "baz")
.build();
assertThat(original.toBuilder().build()).isEqualTo(original);
}
@Test
public void toBuilder_headersModified_notReflectedInOriginal() {
Endpoint original = Endpoint.builder()
.putHeader("foo", "bar")
.build();
original.toBuilder()
.putHeader("foo", "baz")
.build();
assertThat(original.headers().get("foo")).containsExactly("bar");
}
@Test
public void toBuilder_attrsModified_notReflectedInOriginal() {
Endpoint original = Endpoint.builder()
.putAttribute(TEST_STRING_ATTR, "foo")
.build();
original.toBuilder()
.putAttribute(TEST_STRING_ATTR, "bar")
.build();
assertThat(original.attribute(TEST_STRING_ATTR)).isEqualTo("foo");
}
}
| 1,787 |
0 | Create_ds/aws-sdk-java-v2/core/endpoints-spi/src/main/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/core/endpoints-spi/src/main/java/software/amazon/awssdk/endpoints/EndpointProvider.java | /*
* 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.endpoints;
import software.amazon.awssdk.annotations.SdkPublicApi;
/**
* A marker interface for an endpoint provider. An endpoint provider takes as input a set of service-specific parameters, and
* computes an {@link Endpoint} based on the given parameters.
*/
@SdkPublicApi
public interface EndpointProvider {
}
| 1,788 |
0 | Create_ds/aws-sdk-java-v2/core/endpoints-spi/src/main/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/core/endpoints-spi/src/main/java/software/amazon/awssdk/endpoints/EndpointAttributeKey.java | /*
* 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.endpoints;
import java.util.List;
import software.amazon.awssdk.annotations.SdkPublicApi;
/**
* A key for adding and retrieving attributes from an {@link Endpoint} in a typesafe manner.
* @param <T> The type of the attribute.
*/
@SdkPublicApi
public final class EndpointAttributeKey<T> {
private final String name;
private final Class<T> clzz;
public EndpointAttributeKey(String name, Class<T> clzz) {
this.name = name;
this.clzz = clzz;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
EndpointAttributeKey<?> that = (EndpointAttributeKey<?>) o;
if (name != null ? !name.equals(that.name) : that.name != null) {
return false;
}
return clzz != null ? clzz.equals(that.clzz) : that.clzz == null;
}
@Override
public int hashCode() {
int result = name != null ? name.hashCode() : 0;
result = 31 * result + (clzz != null ? clzz.hashCode() : 0);
return result;
}
public static <E> EndpointAttributeKey<List<E>> forList(String name) {
return new EndpointAttributeKey(name, List.class);
}
}
| 1,789 |
0 | Create_ds/aws-sdk-java-v2/core/endpoints-spi/src/main/java/software/amazon/awssdk | Create_ds/aws-sdk-java-v2/core/endpoints-spi/src/main/java/software/amazon/awssdk/endpoints/Endpoint.java | /*
* 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.endpoints;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import software.amazon.awssdk.annotations.SdkPublicApi;
/**
* Represents an endpoint computed by an {@link EndpointProvider}. And endpoint minimally defines the {@code URI}, but may also
* declare any additional headers that needed to be used, and user-defined attributes using an {@link EndpointAttributeKey}.
*/
@SdkPublicApi
public final class Endpoint {
private final URI url;
private final Map<String, List<String>> headers;
private final Map<EndpointAttributeKey<?>, Object> attributes;
private Endpoint(BuilderImpl b) {
this.url = b.url;
this.headers = b.headers;
this.attributes = b.attributes;
}
public URI url() {
return url;
}
public Map<String, List<String>> headers() {
return headers;
}
public Builder toBuilder() {
return new BuilderImpl(this);
}
@SuppressWarnings("unchecked")
public <T> T attribute(EndpointAttributeKey<T> key) {
return (T) attributes.get(key);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Endpoint endpoint = (Endpoint) o;
if (url != null ? !url.equals(endpoint.url) : endpoint.url != null) {
return false;
}
if (headers != null ? !headers.equals(endpoint.headers) : endpoint.headers != null) {
return false;
}
return attributes != null ? attributes.equals(endpoint.attributes) : endpoint.attributes == null;
}
@Override
public int hashCode() {
int result = url != null ? url.hashCode() : 0;
result = 31 * result + (headers != null ? headers.hashCode() : 0);
result = 31 * result + (attributes != null ? attributes.hashCode() : 0);
return result;
}
public static Builder builder() {
return new BuilderImpl();
}
public interface Builder {
Builder url(URI url);
Builder putHeader(String name, String value);
<T> Builder putAttribute(EndpointAttributeKey<T> key, T value);
Endpoint build();
}
private static class BuilderImpl implements Builder {
private URI url;
private final Map<String, List<String>> headers = new HashMap<>();
private final Map<EndpointAttributeKey<?>, Object> attributes = new HashMap<>();
private BuilderImpl() {
}
private BuilderImpl(Endpoint e) {
this.url = e.url;
if (e.headers != null) {
e.headers.forEach((n, v) -> {
this.headers.put(n, new ArrayList<>(v));
});
}
this.attributes.putAll(e.attributes);
}
@Override
public Builder url(URI url) {
this.url = url;
return this;
}
@Override
public Builder putHeader(String name, String value) {
List<String> values = this.headers.computeIfAbsent(name, (n) -> new ArrayList<>());
values.add(value);
return this;
}
@Override
public <T> Builder putAttribute(EndpointAttributeKey<T> key, T value) {
this.attributes.put(key, value);
return this;
}
@Override
public Endpoint build() {
return new Endpoint(this);
}
}
}
| 1,790 |
0 | Create_ds/aws-sdk-java-v2/core/http-auth-aws-crt/src/main/java/software/amazon/awssdk/http/auth/aws | Create_ds/aws-sdk-java-v2/core/http-auth-aws-crt/src/main/java/software/amazon/awssdk/http/auth/aws/crt/HttpAuthAwsCrt.java | /*
* 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.http.auth.aws.crt;
import software.amazon.awssdk.annotations.SdkProtectedApi;
/**
* This is a place-holder class for this module, http-auth-aws-crt. In the event that we decide to move CRT-v4a signer
* logic back to this dedicated module, no issues will arise. This module should be an optional dependency in consumers
* (http-auth-aws), and should bring in the required dependencies (aws-crt).
*/
@SdkProtectedApi
public final class HttpAuthAwsCrt {
}
| 1,791 |
0 | Create_ds/aws-sdk-java-v2/core/auth-crt/src/test/java/software/amazon/awssdk/authcrt | Create_ds/aws-sdk-java-v2/core/auth-crt/src/test/java/software/amazon/awssdk/authcrt/signer/AwsCrtV4aSignerTest.java | /*
* 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.authcrt.signer;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertTrue;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.junit.MockitoJUnitRunner;
import software.amazon.awssdk.authcrt.signer.internal.SigningConfigProvider;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.crt.auth.signing.AwsSigningConfig;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.regions.Region;
/**
* Functional tests for the Sigv4a signer. These tests call the CRT native signer code.
*/
@RunWith(MockitoJUnitRunner.class)
public class AwsCrtV4aSignerTest {
private SigningConfigProvider configProvider;
private AwsCrtV4aSigner v4aSigner;
@Before
public void setup() {
configProvider = new SigningConfigProvider();
v4aSigner = AwsCrtV4aSigner.create();
}
@Test
public void hostHeaderExcludesStandardHttpPort() {
SigningTestCase testCase = SignerTestUtils.createBasicHeaderSigningTestCase();
ExecutionAttributes executionAttributes = SignerTestUtils.buildBasicExecutionAttributes(testCase);
SdkHttpFullRequest request = testCase.requestBuilder.protocol("http")
.port(80)
.build();
SdkHttpFullRequest signed = v4aSigner.sign(request, executionAttributes);
assertThat(signed.firstMatchingHeader("Host")).hasValue("demo.us-east-1.amazonaws.com");
}
@Test
public void hostHeaderExcludesStandardHttpsPort() {
SigningTestCase testCase = SignerTestUtils.createBasicHeaderSigningTestCase();
ExecutionAttributes executionAttributes = SignerTestUtils.buildBasicExecutionAttributes(testCase);
SdkHttpFullRequest request = testCase.requestBuilder.protocol("https")
.port(443)
.build();
SdkHttpFullRequest signed = v4aSigner.sign(request, executionAttributes);
assertThat(signed.firstMatchingHeader("Host")).hasValue("demo.us-east-1.amazonaws.com");
}
@Test
public void hostHeaderIncludesNonStandardPorts() {
SigningTestCase testCase = SignerTestUtils.createBasicHeaderSigningTestCase();
ExecutionAttributes executionAttributes = SignerTestUtils.buildBasicExecutionAttributes(testCase);
SdkHttpFullRequest request = testCase.requestBuilder.protocol("http")
.port(443)
.build();
SdkHttpFullRequest signed = v4aSigner.sign(request, executionAttributes);
assertThat(signed.firstMatchingHeader("Host")).hasValue("demo.us-east-1.amazonaws.com:443");
}
@Test
public void testHeaderSigning() {
SigningTestCase testCase = SignerTestUtils.createBasicHeaderSigningTestCase();
ExecutionAttributes executionAttributes = SignerTestUtils.buildBasicExecutionAttributes(testCase);
SdkHttpFullRequest request = testCase.requestBuilder.build();
SdkHttpFullRequest signed = v4aSigner.sign(request, executionAttributes);
String authHeader = signed.firstMatchingHeader("Authorization").get();
String signatureKey = "Signature=";
String signatureValue = authHeader.substring(authHeader.indexOf(signatureKey) + signatureKey.length());
AwsSigningConfig signingConfig = configProvider.createCrtSigningConfig(executionAttributes);
String regionHeader = signed.firstMatchingHeader("X-Amz-Region-Set").get();
assertThat(regionHeader).isEqualTo(Region.AWS_GLOBAL.id());
assertTrue(SignerTestUtils.verifyEcdsaSignature(request, testCase.expectedCanonicalRequest, signingConfig, signatureValue));
}
@Test
public void testQuerySigning() {
SigningTestCase testCase = SignerTestUtils.createBasicQuerySigningTestCase();
ExecutionAttributes executionAttributes = SignerTestUtils.buildBasicExecutionAttributes(testCase);
SdkHttpFullRequest request = testCase.requestBuilder.build();
SdkHttpFullRequest signed = v4aSigner.presign(request, executionAttributes);
List<String> signatureValues = signed.rawQueryParameters().get("X-Amz-Signature");
String signatureValue = signatureValues.get(0);
List<String> regionHeader = signed.rawQueryParameters().get("X-Amz-Region-Set");
assertThat(regionHeader.get(0)).isEqualTo(Region.AWS_GLOBAL.id());
AwsSigningConfig signingConfig = configProvider.createCrtPresigningConfig(executionAttributes);
assertTrue(SignerTestUtils.verifyEcdsaSignature(request, testCase.expectedCanonicalRequest, signingConfig, signatureValue));
}
}
| 1,792 |
0 | Create_ds/aws-sdk-java-v2/core/auth-crt/src/test/java/software/amazon/awssdk/authcrt | Create_ds/aws-sdk-java-v2/core/auth-crt/src/test/java/software/amazon/awssdk/authcrt/signer/AwsCrtS3V4aSignerTest.java | /*
* 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.authcrt.signer;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertTrue;
import java.net.URI;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.junit.MockitoJUnitRunner;
import software.amazon.awssdk.auth.signer.internal.chunkedencoding.AwsSignedChunkedEncodingInputStream;
import software.amazon.awssdk.authcrt.signer.internal.SigningConfigProvider;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.regions.Region;
/**
* Functional tests for the S3 specific Sigv4a signer. These tests call the CRT native signer code.
*/
@RunWith(MockitoJUnitRunner.class)
public class AwsCrtS3V4aSignerTest {
private SigningConfigProvider configProvider;
private AwsCrtS3V4aSigner s3V4aSigner;
@Before
public void setup() {
configProvider = new SigningConfigProvider();
s3V4aSigner = AwsCrtS3V4aSigner.create();
}
@Test
public void testS3Signing() {
SigningTestCase testCase = SignerTestUtils.createBasicHeaderSigningTestCase();
ExecutionAttributes executionAttributes = SignerTestUtils.buildBasicExecutionAttributes(testCase);
SdkHttpFullRequest request = testCase.requestBuilder.build();
SdkHttpFullRequest signedRequest = s3V4aSigner.sign(request, executionAttributes);
assertThat(signedRequest.firstMatchingHeader("Authorization")).isPresent();
}
@Test
public void testS3ChunkedSigning() {
SigningTestCase testCase = SignerTestUtils.createBasicChunkedSigningTestCase();
ExecutionAttributes executionAttributes = SignerTestUtils.buildBasicExecutionAttributes(testCase);
SdkHttpFullRequest.Builder requestBuilder = testCase.requestBuilder;
requestBuilder.uri(URI.create("http://demo.us-east-1.amazonaws.com"));
SdkHttpFullRequest request = requestBuilder.build();
SdkHttpFullRequest signedRequest = s3V4aSigner.sign(request, executionAttributes);
assertThat(signedRequest.firstMatchingHeader("Authorization")).isPresent();
assertThat(signedRequest.contentStreamProvider()).isPresent();
assertThat(signedRequest.contentStreamProvider().get().newStream()).isInstanceOf(AwsSignedChunkedEncodingInputStream.class);
}
@Test
public void testS3Presigning() {
SigningTestCase testCase = SignerTestUtils.createBasicQuerySigningTestCase();
ExecutionAttributes executionAttributes = SignerTestUtils.buildBasicExecutionAttributes(testCase);
SdkHttpFullRequest request = testCase.requestBuilder.build();
SdkHttpFullRequest signed = s3V4aSigner.presign(request, executionAttributes);
List<String> regionHeader = signed.rawQueryParameters().get("X-Amz-Region-Set");
assertThat(regionHeader.get(0)).isEqualTo(Region.AWS_GLOBAL.id());
}
}
| 1,793 |
0 | Create_ds/aws-sdk-java-v2/core/auth-crt/src/test/java/software/amazon/awssdk/authcrt | Create_ds/aws-sdk-java-v2/core/auth-crt/src/test/java/software/amazon/awssdk/authcrt/signer/SignerTestUtils.java | /*
* 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.authcrt.signer;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static software.amazon.awssdk.authcrt.signer.internal.SigningUtils.SIGNING_CLOCK;
import java.io.ByteArrayInputStream;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.time.Clock;
import java.time.Instant;
import java.time.ZoneId;
import java.util.Arrays;
import java.util.List;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.signer.AwsSignerExecutionAttribute;
import software.amazon.awssdk.authcrt.signer.internal.CrtHttpRequestConverter;
import software.amazon.awssdk.authcrt.signer.internal.SigningUtils;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.crt.auth.signing.AwsSigningConfig;
import software.amazon.awssdk.crt.auth.signing.AwsSigningUtils;
import software.amazon.awssdk.crt.http.HttpRequest;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.http.SdkHttpMethod;
import software.amazon.awssdk.regions.Region;
public class SignerTestUtils {
private static final String TEST_ACCESS_KEY_ID = "AKIDEXAMPLE";
private static final String TEST_SECRET_ACCESS_KEY = "wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY";
private static final String TEST_VERIFICATION_PUB_X = "b6618f6a65740a99e650b33b6b4b5bd0d43b176d721a3edfea7e7d2d56d936b1";
private static final String TEST_VERIFICATION_PUB_Y = "865ed22a7eadc9c5cb9d2cbaca1b3699139fedc5043dc6661864218330c8e518";
private static final String AUTH_SIGNED_HEADER_KEY = "SignedHeaders=";
private static final String AUTH_SIGNATURE_KEY = "Signature=";
public static boolean verifyEcdsaSignature(SdkHttpFullRequest request,
String expectedCanonicalRequest,
AwsSigningConfig signingConfig,
String signatureValue) {
CrtHttpRequestConverter requestConverter = new CrtHttpRequestConverter();
HttpRequest crtRequest = requestConverter.requestToCrt(SigningUtils.sanitizeSdkRequestForCrtSigning(request));
return AwsSigningUtils.verifySigv4aEcdsaSignature(crtRequest, expectedCanonicalRequest, signingConfig,
signatureValue.getBytes(), TEST_VERIFICATION_PUB_X, TEST_VERIFICATION_PUB_Y);
}
public static AwsBasicCredentials createCredentials() {
return AwsBasicCredentials.create(TEST_ACCESS_KEY_ID, TEST_SECRET_ACCESS_KEY);
}
public static ExecutionAttributes buildBasicExecutionAttributes(SigningTestCase testCase) {
ExecutionAttributes executionAttributes = new ExecutionAttributes();
executionAttributes.putAttribute(SIGNING_CLOCK, Clock.fixed(testCase.signingTime, ZoneId.systemDefault()));
executionAttributes.putAttribute(AwsSignerExecutionAttribute.SERVICE_SIGNING_NAME, testCase.signingName);
executionAttributes.putAttribute(AwsSignerExecutionAttribute.SIGNING_REGION, Region.AWS_GLOBAL);
executionAttributes.putAttribute(AwsSignerExecutionAttribute.AWS_CREDENTIALS, testCase.credentials);
return executionAttributes;
}
public static SigningTestCase createBasicHeaderSigningTestCase() {
SigningTestCase testCase = new SigningTestCase();
String data = "{\"TableName\": \"foo\"}";
testCase.requestBuilder = createHttpPostRequest(data);
testCase.signingName = "demo";
testCase.regionSet = "aws-global";
testCase.signingTime = Instant.ofEpochSecond(1596476903);
testCase.credentials = createCredentials();
testCase.expectedCanonicalRequest = "POST\n" +
"/\n" +
"\n" +
"host:demo.us-east-1.amazonaws.com\n" +
"x-amz-archive-description:test test\n" +
"x-amz-date:20200803T174823Z\n" +
"x-amz-region-set:aws-global\n" +
"\n" +
"host;x-amz-archive-description;x-amz-date;x-amz-region-set\n" +
"a15c8292b1d12abbbbe4148605f7872fbdf645618fee5ab0e8072a7b34f155e2";
return testCase;
}
public static SigningTestCase createBasicChunkedSigningTestCase() {
SigningTestCase testCase = new SigningTestCase();
String data = "{\"TableName\": \"foo\"}";
testCase.requestBuilder = createHttpPostRequest(data);
testCase.signingName = "demo";
testCase.regionSet = "aws-global";
testCase.signingTime = Instant.ofEpochSecond(1596476903);
testCase.credentials = createCredentials();
testCase.expectedCanonicalRequest = "POST\n" +
"/\n" +
"\n" +
"host:demo.us-east-1.amazonaws.com\n" +
"x-amz-archive-description:test test\n" +
"x-amz-date:20200803T174823Z\n" +
"x-amz-decoded-content-length\n" +
"x-amz-region-set:aws-global\n" +
"\n" +
"host;x-amz-archive-description;x-amz-date;x-amz-decoded-content-length;x-amz-region-set\n" +
"";
return testCase;
}
public static SigningTestCase createBasicQuerySigningTestCase() {
SigningTestCase testCase = new SigningTestCase();
testCase.requestBuilder = SdkHttpFullRequest.builder()
.method(SdkHttpMethod.GET)
.putHeader("Host", "testing.us-east-1.amazonaws.com")
.encodedPath("/test%20path/help")
.uri(URI.create("http://testing.us-east-1.amazonaws.com"));
testCase.signingName = "testing";
testCase.regionSet = "aws-global";
testCase.signingTime = Instant.ofEpochSecond(1596476801);
testCase.credentials = createCredentials();
testCase.expectedCanonicalRequest = "GET\n" +
"/test%2520path/help\n" +
"X-Amz-Algorithm=AWS4-ECDSA-P256-SHA256&X-Amz-Credential=AKIDEXAMPLE%2F20200803%2Ftesting%2Faws4_request&X-Amz-Date=20200803T174641Z&X-Amz-Expires=604800&X-Amz-Region-Set=aws-global&X-Amz-SignedHeaders=host\n" +
"host:testing.us-east-1.amazonaws.com\n" +
"\n" +
"host\n" +
"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
testCase.expectedS3PresignCanonicalRequest = "GET\n" +
"/test%2520path/help\n" +
"X-Amz-Algorithm=AWS4-ECDSA-P256-SHA256&X-Amz-Credential=AKIDEXAMPLE%2F20200803%2Ftesting%2Faws4_request&X-Amz-Date=20200803T174641Z&X-Amz-Expires=604800&X-Amz-Region-Set=aws-global&X-Amz-SignedHeaders=host\n" +
"host:testing.us-east-1.amazonaws.com\n" +
"\n" +
"host\n" +
"UNSIGNED-PAYLOAD";
return testCase;
}
public static String extractSignatureFromAuthHeader(SdkHttpFullRequest signedRequest) {
String authHeader = signedRequest.firstMatchingHeader("Authorization").get();
return authHeader.substring(authHeader.indexOf(AUTH_SIGNATURE_KEY) + AUTH_SIGNATURE_KEY.length());
}
public static List<String> extractSignedHeadersFromAuthHeader(SdkHttpFullRequest signedRequest) {
String authHeader = signedRequest.firstMatchingHeader("Authorization").get();
String headers = authHeader.substring(authHeader.indexOf(AUTH_SIGNED_HEADER_KEY) + AUTH_SIGNED_HEADER_KEY.length(),
authHeader.indexOf(AUTH_SIGNATURE_KEY) - 1);
return Arrays.asList(headers.split(";"));
}
public static SdkHttpFullRequest.Builder createHttpPostRequest(String data) {
return SdkHttpFullRequest.builder()
.contentStreamProvider(() -> new ByteArrayInputStream(data.getBytes(StandardCharsets.UTF_8)))
.method(SdkHttpMethod.POST)
.putHeader("x-amz-archive-description", "test test")
.putHeader("Host", "demo.us-east-1.amazonaws.com")
.encodedPath("/")
.uri(URI.create("https://demo.us-east-1.amazonaws.com"));
}
public static SdkHttpFullRequest createSignedHttpRequest(String data) {
SdkHttpFullRequest.Builder requestBuilder = createHttpPostRequest(data);
requestBuilder.putHeader("Authorization", "AWS4-ECDSA-P256-SHA256 Credential=AKIDEXAMPLE/20200803/demo/aws4_request, SignedHeaders=host;x-amz-archive-description;x-amz-date;x-amz-region-set, Signature=304502201ee492c60af1667b9c1adfbafb4dfebedca45ed7f9c17711bc73bd2c0ebdbb4b022100e1108c7749acf67bb8c2e5fcf11f751fd86f8fde9bd646a47b4897023ca348d9");
requestBuilder.putHeader("X-Amz-Date", "20200803T174823Z");
requestBuilder.putHeader("X-Amz-Region-Set", "aws-global");
return requestBuilder.build();
}
public static SdkHttpFullRequest createSignedPayloadHttpRequest(String data) {
SdkHttpFullRequest.Builder requestBuilder = createHttpPostRequest(data);
requestBuilder.putHeader("Authorization", "AWS4-ECDSA-P256-SHA256 Credential=AKIDEXAMPLE/20200803/demo/aws4_request, SignedHeaders=content-length;host;x-amz-archive-description;x-amz-content-sha256;x-amz-date;x-amz-decoded-content-length;x-amz-region-set, Signature=3046022100e3594ebc9ddfe327ca5127bbce72dd2b72965c33df36e529996edff1d7b59811022100e34cb9a2a68e82f6ac86e3359a758c546cdfb59807207dc6ebfedb44abbc4ca7");
requestBuilder.putHeader("X-Amz-Date", "20200803T174823Z");
requestBuilder.putHeader("X-Amz-Region-Set", "aws-global");
requestBuilder.putHeader("x-amz-decoded-content-length", "20");
requestBuilder.putHeader("Content-Length", "353");
return requestBuilder.build();
}
public static SdkHttpFullRequest createPresignedPayloadHttpRequest(String data) {
SdkHttpFullRequest.Builder requestBuilder = createHttpPostRequest(data);
requestBuilder.putRawQueryParameter("X-Amz-Signature", "signature");
return requestBuilder.build();
}
}
| 1,794 |
0 | Create_ds/aws-sdk-java-v2/core/auth-crt/src/test/java/software/amazon/awssdk/authcrt | Create_ds/aws-sdk-java-v2/core/auth-crt/src/test/java/software/amazon/awssdk/authcrt/signer/SigningTestCase.java | /*
* 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.authcrt.signer;
import java.time.Instant;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.http.SdkHttpFullRequest;
public class SigningTestCase {
public SdkHttpFullRequest.Builder requestBuilder;
public String expectedCanonicalRequest;
public String expectedS3PresignCanonicalRequest;
public String signingName;
public String regionSet;
public Instant signingTime;
public AwsBasicCredentials credentials;
}
| 1,795 |
0 | Create_ds/aws-sdk-java-v2/core/auth-crt/src/test/java/software/amazon/awssdk/authcrt/signer | Create_ds/aws-sdk-java-v2/core/auth-crt/src/test/java/software/amazon/awssdk/authcrt/signer/internal/AwsCrtS3V4aSignerSigningScopeTest.java | /*
* 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.authcrt.signer.internal;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.List;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.auth.signer.AwsSignerExecutionAttribute;
import software.amazon.awssdk.authcrt.signer.AwsCrtS3V4aSigner;
import software.amazon.awssdk.authcrt.signer.SignerTestUtils;
import software.amazon.awssdk.authcrt.signer.SigningTestCase;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.regions.RegionScope;
public class AwsCrtS3V4aSignerSigningScopeTest extends BaseSigningScopeTest {
@Test
public void signing_chunkedEncoding_regionalScope_present_overrides() {
SigningTestCase testCase = SignerTestUtils.createBasicChunkedSigningTestCase();
SdkHttpFullRequest signedRequest = signRequestWithScope(testCase, null, RegionScope.GLOBAL);
String regionHeader = signedRequest.firstMatchingHeader("X-Amz-Region-Set").get();
assertThat(regionHeader).isEqualTo(RegionScope.GLOBAL.id());
}
@Test
public void testS3Presigning() {
SigningTestCase testCase = SignerTestUtils.createBasicQuerySigningTestCase();
SdkHttpFullRequest signedRequest = presignRequestWithScope(testCase, null, RegionScope.GLOBAL);
List<String> regionHeader = signedRequest.rawQueryParameters().get("X-Amz-Region-Set");
assertThat(regionHeader.get(0)).isEqualTo(RegionScope.GLOBAL.id());
}
protected SdkHttpFullRequest signRequestWithScope(SigningTestCase testCase, RegionScope defaultRegionScope,
RegionScope regionScope) {
ExecutionAttributes executionAttributes = SignerTestUtils.buildBasicExecutionAttributes(testCase);
if (regionScope != null) {
executionAttributes.putAttribute(AwsSignerExecutionAttribute.SIGNING_REGION_SCOPE, regionScope);
}
SdkHttpFullRequest request = testCase.requestBuilder.build();
return AwsCrtS3V4aSigner.builder().defaultRegionScope(defaultRegionScope).build().sign(request, executionAttributes);
}
protected SdkHttpFullRequest presignRequestWithScope(SigningTestCase testCase, RegionScope defaultRegionScope,
RegionScope regionScope) {
ExecutionAttributes executionAttributes = SignerTestUtils.buildBasicExecutionAttributes(testCase);
if (regionScope != null) {
executionAttributes.putAttribute(AwsSignerExecutionAttribute.SIGNING_REGION_SCOPE, regionScope);
}
SdkHttpFullRequest request = testCase.requestBuilder.build();
return AwsCrtS3V4aSigner.builder().defaultRegionScope(defaultRegionScope).build().presign(request, executionAttributes);
}
}
| 1,796 |
0 | Create_ds/aws-sdk-java-v2/core/auth-crt/src/test/java/software/amazon/awssdk/authcrt/signer | Create_ds/aws-sdk-java-v2/core/auth-crt/src/test/java/software/amazon/awssdk/authcrt/signer/internal/AwsChunkedEncodingInputStreamTest.java | /*
* 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.authcrt.signer.internal;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.when;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import software.amazon.awssdk.core.checksums.Algorithm;
import software.amazon.awssdk.core.checksums.SdkChecksum;
import software.amazon.awssdk.core.internal.chunked.AwsChunkedEncodingConfig;
import software.amazon.awssdk.auth.signer.internal.chunkedencoding.AwsSignedChunkedEncodingInputStream;
import software.amazon.awssdk.authcrt.signer.internal.chunkedencoding.AwsS3V4aChunkSigner;
import software.amazon.awssdk.utils.BinaryUtils;
/**
* Runs unit tests that check that the class AwsChunkedEncodingInputStream supports params required for Sigv4a chunk
* signing.
*/
@RunWith(MockitoJUnitRunner.class)
public class AwsChunkedEncodingInputStreamTest {
private static final String REQUEST_SIGNATURE;
private static final String CHUNK_SIGNATURE_1;
private static final String CHUNK_SIGNATURE_2;
private static final String CHUNK_SIGNATURE_3;
private static final String CHECKSUM_CHUNK_SIGNATURE_3;
private static final String SIGNATURE_KEY = "chunk-signature=";
private static final String EMPTY_STRING = "";
private static final String CRLF = "\r\n";
private static final int DEFAULT_CHUNK_SIZE = 128 * 1024;
private static final int SIGV4A_SIGNATURE_LENGTH = 144;
static {
byte[] tmp = new byte[140];
Arrays.fill(tmp, (byte) 0x2A);
REQUEST_SIGNATURE = new String(tmp);
tmp = new byte[144];
Arrays.fill(tmp, (byte) 0x2B);
CHUNK_SIGNATURE_1 = new String(tmp);
tmp = new byte[144];
Arrays.fill(tmp, (byte) 0x2C);
CHUNK_SIGNATURE_2 = new String(tmp);
tmp = new byte[144];
Arrays.fill(tmp, (byte) 0x2E);
CHUNK_SIGNATURE_3 = new String(tmp);
tmp = new byte[144];
Arrays.fill(tmp, (byte) 0x2F);
CHECKSUM_CHUNK_SIGNATURE_3 = new String(tmp);
}
@Mock
AwsS3V4aChunkSigner chunkSigner;
/**
* maxSizeChunks = 0, remainingBytes = 10;
* chunklen(10) = 1 + 17 + 144 + 2 + 10 + 2 = 176
* chunklen(0) = 1 + 17 + 144 + 2 + 0 + 2 = 166
* total = 0 * chunklen(default_chunk_size) + chunklen(10) + chunklen(0) = 342
*/
@Test
public void streamContentLength_smallObject_calculatedCorrectly() {
long streamContentLength =
AwsSignedChunkedEncodingInputStream.calculateStreamContentLength(10,
AwsS3V4aChunkSigner.getSignatureLength(),
AwsChunkedEncodingConfig.create());
assertThat(streamContentLength).isEqualTo(342);
}
/**
* maxSizeChunks = 1, remainingBytes = 1;
* chunklen(131072) = 5 + 17 + 144 + 2 + 131072 + 2 = 131242
* chunklen(1) = 1 + 17 + 144 + 2 + 10 + 2 = 176
* chunklen(0) = 1 + 17 + 144 + 2 + 0 + 2 = 166
* total = 1 * chunklen(default_chunk_size) + chunklen(10) + chunklen(0) = 131584
*/
@Test
public void streamContentLength_largeObject_calculatedCorrectly() {
long streamContentLength =
AwsSignedChunkedEncodingInputStream.calculateStreamContentLength(DEFAULT_CHUNK_SIZE + 10,
AwsS3V4aChunkSigner.getSignatureLength(),
AwsChunkedEncodingConfig.create());
assertThat(streamContentLength).isEqualTo(131584);
}
@Test
public void streamContentLength_differentChunkSize_calculatedCorrectly() {
int chunkSize = 64 * 1024;
AwsChunkedEncodingConfig chunkConfig = AwsChunkedEncodingConfig.builder().chunkSize(chunkSize).build();
long streamContentLength =
AwsSignedChunkedEncodingInputStream.calculateStreamContentLength(chunkSize + 10,
AwsS3V4aChunkSigner.getSignatureLength(),
chunkConfig);
assertThat(streamContentLength).isEqualTo(66048);
}
@Test(expected = IllegalArgumentException.class)
public void streamContentLength_negative_throwsException() {
AwsSignedChunkedEncodingInputStream.calculateStreamContentLength(-1,
AwsS3V4aChunkSigner.getSignatureLength(),
AwsChunkedEncodingConfig.create());
}
@Test
public void chunkedEncodingStream_smallObject_createsCorrectChunks() throws IOException {
when(chunkSigner.signChunk(any(), any())).thenReturn(CHUNK_SIGNATURE_1)
.thenReturn(CHUNK_SIGNATURE_2);
String chunkData = "helloworld";
ByteArrayInputStream input = new ByteArrayInputStream(chunkData.getBytes());
AwsSignedChunkedEncodingInputStream stream = AwsSignedChunkedEncodingInputStream.builder()
.inputStream(input)
.headerSignature(REQUEST_SIGNATURE)
.awsChunkSigner(chunkSigner)
.awsChunkedEncodingConfig(AwsChunkedEncodingConfig.create())
.build();
int expectedChunks = 2;
consumeAndVerify(stream, expectedChunks,false);
Mockito.verify(chunkSigner, times(1)).signChunk(chunkData.getBytes(StandardCharsets.UTF_8), REQUEST_SIGNATURE);
Mockito.verify(chunkSigner, times(1)).signChunk(EMPTY_STRING.getBytes(StandardCharsets.UTF_8), CHUNK_SIGNATURE_1);
}
@Test
public void chunkedEncodingStream_largeObject_createsCorrectChunks() throws IOException {
when(chunkSigner.signChunk(any(), any())).thenReturn(CHUNK_SIGNATURE_1)
.thenReturn(CHUNK_SIGNATURE_2)
.thenReturn(CHUNK_SIGNATURE_3);
String chunk1Data = StringUtils.repeat("a", DEFAULT_CHUNK_SIZE);
String chunk2Data = "a";
ByteArrayInputStream input = new ByteArrayInputStream(chunk1Data.concat(chunk2Data).getBytes());
AwsSignedChunkedEncodingInputStream stream = AwsSignedChunkedEncodingInputStream.builder()
.inputStream(input)
.headerSignature(REQUEST_SIGNATURE)
.awsChunkSigner(chunkSigner)
.awsChunkedEncodingConfig(AwsChunkedEncodingConfig.create())
.build();
int expectedChunks = 3;
consumeAndVerify(stream, expectedChunks,false);
Mockito.verify(chunkSigner, times(1)).signChunk(chunk1Data.getBytes(StandardCharsets.UTF_8), REQUEST_SIGNATURE);
Mockito.verify(chunkSigner, times(1)).signChunk(chunk2Data.getBytes(StandardCharsets.UTF_8), CHUNK_SIGNATURE_1);
Mockito.verify(chunkSigner, times(1)).signChunk(EMPTY_STRING.getBytes(StandardCharsets.UTF_8), CHUNK_SIGNATURE_2);
}
@Test
public void chunkedEncodingStream_differentChunkSize_createsCorrectChunks() throws IOException {
when(chunkSigner.signChunk(any(), any())).thenReturn(CHUNK_SIGNATURE_1)
.thenReturn(CHUNK_SIGNATURE_2)
.thenReturn(CHUNK_SIGNATURE_3);
int chunkSize = 64 * 1024;
AwsChunkedEncodingConfig chunkConfig = AwsChunkedEncodingConfig.builder().chunkSize(chunkSize).build();
String chunk1Data = StringUtils.repeat("a", chunkSize);
String chunk2Data = "a";
ByteArrayInputStream input = new ByteArrayInputStream(chunk1Data.concat(chunk2Data).getBytes());
AwsSignedChunkedEncodingInputStream stream = AwsSignedChunkedEncodingInputStream.builder()
.inputStream(input)
.headerSignature(REQUEST_SIGNATURE)
.awsChunkSigner(chunkSigner)
.awsChunkedEncodingConfig(chunkConfig)
.build();
int expectedChunks = 3;
consumeAndVerify(stream, expectedChunks,false);
Mockito.verify(chunkSigner, times(1)).signChunk(chunk1Data.getBytes(StandardCharsets.UTF_8), REQUEST_SIGNATURE);
Mockito.verify(chunkSigner, times(1)).signChunk(chunk2Data.getBytes(StandardCharsets.UTF_8), CHUNK_SIGNATURE_1);
Mockito.verify(chunkSigner, times(1)).signChunk(EMPTY_STRING.getBytes(StandardCharsets.UTF_8), CHUNK_SIGNATURE_2);
}
@Test
public void chunkedEncodingStream_emptyString_createsCorrectChunks() throws IOException {
when(chunkSigner.signChunk(any(), any())).thenReturn(CHUNK_SIGNATURE_1);
String chunkData = EMPTY_STRING;
ByteArrayInputStream input = new ByteArrayInputStream(chunkData.getBytes());
AwsSignedChunkedEncodingInputStream stream = AwsSignedChunkedEncodingInputStream.builder()
.inputStream(input)
.headerSignature(REQUEST_SIGNATURE)
.awsChunkSigner(chunkSigner)
.awsChunkedEncodingConfig(AwsChunkedEncodingConfig.create())
.build();
int expectedChunks = 1;
consumeAndVerify(stream, expectedChunks,false);
Mockito.verify(chunkSigner, times(1)).signChunk(chunkData.getBytes(StandardCharsets.UTF_8), REQUEST_SIGNATURE);
}
@Test
public void chunkedEncodingStream_smallObject_createsCorrectChunks_and_checksum() throws IOException {
when(chunkSigner.signChunk(any(), any())).thenReturn(CHUNK_SIGNATURE_1)
.thenReturn(CHUNK_SIGNATURE_2);
when(chunkSigner.signChecksumChunk(any(), any(), any())).thenReturn(CHECKSUM_CHUNK_SIGNATURE_3);
String payloadData = "helloworld";
SdkChecksum sdkChecksum = SdkChecksum.forAlgorithm(Algorithm.CRC32);
sdkChecksum.update(payloadData.getBytes(StandardCharsets.UTF_8));
ByteArrayInputStream input = new ByteArrayInputStream(payloadData.getBytes());
AwsSignedChunkedEncodingInputStream stream =
AwsSignedChunkedEncodingInputStream.builder()
.inputStream(input)
.sdkChecksum(SdkChecksum.forAlgorithm(Algorithm.CRC32))
.checksumHeaderForTrailer("x-amz-checksum-crc32")
.headerSignature(REQUEST_SIGNATURE)
.awsChunkSigner(chunkSigner)
.awsChunkedEncodingConfig(AwsChunkedEncodingConfig.create())
.build();
int expectedChunks = 2;
consumeAndVerify(stream, expectedChunks, true);
Mockito.verify(chunkSigner, times(1)).signChunk(payloadData.getBytes(StandardCharsets.UTF_8), REQUEST_SIGNATURE);
Mockito.verify(chunkSigner, times(1)).signChunk(EMPTY_STRING.getBytes(StandardCharsets.UTF_8), CHUNK_SIGNATURE_1);
Mockito.verify(chunkSigner, times(1))
.signChecksumChunk(sdkChecksum.getChecksumBytes(),CHUNK_SIGNATURE_2, "x-amz-checksum-crc32" );
}
@Test
public void chunkedEncodingStream_largeObject_createsCorrectChunks__with_checksums() throws IOException {
when(chunkSigner.signChunk(any(), any())).thenReturn(CHUNK_SIGNATURE_1)
.thenReturn(CHUNK_SIGNATURE_2)
.thenReturn(CHUNK_SIGNATURE_3);
when(chunkSigner.signChecksumChunk(any(), any(), any())).thenReturn(CHECKSUM_CHUNK_SIGNATURE_3);
String chunk1Data = StringUtils.repeat("a", DEFAULT_CHUNK_SIZE);
String chunk2Data = "a";
SdkChecksum sdkChecksum = SdkChecksum.forAlgorithm(Algorithm.CRC32);
sdkChecksum.update(chunk1Data.getBytes(StandardCharsets.UTF_8));
sdkChecksum.update(chunk2Data.getBytes(StandardCharsets.UTF_8));
ByteArrayInputStream input = new ByteArrayInputStream(chunk1Data.concat(chunk2Data).getBytes());
AwsSignedChunkedEncodingInputStream stream =
AwsSignedChunkedEncodingInputStream.builder()
.inputStream(input)
.sdkChecksum(SdkChecksum.forAlgorithm(Algorithm.CRC32))
.checksumHeaderForTrailer("x-amz-checksum-crc32")
.headerSignature(REQUEST_SIGNATURE)
.awsChunkSigner(chunkSigner)
.awsChunkedEncodingConfig(AwsChunkedEncodingConfig.create())
.build();
int expectedChunks = 3;
consumeAndVerify(stream, expectedChunks, true);
Mockito.verify(chunkSigner, times(1)).signChunk(chunk1Data.getBytes(StandardCharsets.UTF_8), REQUEST_SIGNATURE);
Mockito.verify(chunkSigner, times(1)).signChunk(chunk2Data.getBytes(StandardCharsets.UTF_8), CHUNK_SIGNATURE_1);
Mockito.verify(chunkSigner, times(1)).signChunk(EMPTY_STRING.getBytes(StandardCharsets.UTF_8), CHUNK_SIGNATURE_2);
Mockito.verify(chunkSigner, times(1))
.signChecksumChunk(sdkChecksum.getChecksumBytes(), CHUNK_SIGNATURE_3, "x-amz-checksum-crc32");
}
@Test
public void chunkedEncodingStream_emptyString_createsCorrectChunks_checksum() throws IOException {
when(chunkSigner.signChunk(any(), any())).thenReturn(CHUNK_SIGNATURE_1);
when(chunkSigner.signChecksumChunk(any(), any(), any())).thenReturn(CHECKSUM_CHUNK_SIGNATURE_3);
String chunkData = EMPTY_STRING;
SdkChecksum sdkChecksum = SdkChecksum.forAlgorithm(Algorithm.CRC32);
byte[] bytes = chunkData.getBytes(StandardCharsets.UTF_8);
ByteArrayInputStream input = new ByteArrayInputStream(chunkData.getBytes());
AwsSignedChunkedEncodingInputStream stream =
AwsSignedChunkedEncodingInputStream.builder()
.inputStream(input)
.sdkChecksum(SdkChecksum.forAlgorithm(Algorithm.CRC32))
.checksumHeaderForTrailer("x-amz-checksum-crc32")
.headerSignature(REQUEST_SIGNATURE)
.awsChunkSigner(chunkSigner)
.awsChunkedEncodingConfig(AwsChunkedEncodingConfig.create())
.build();
int expectedChunks = 1;
consumeAndVerify(stream, expectedChunks, true);
Mockito.verify(chunkSigner, times(1)).signChunk(bytes, REQUEST_SIGNATURE);
Mockito.verify(chunkSigner, times(1))
.signChecksumChunk(sdkChecksum.getChecksumBytes(), CHUNK_SIGNATURE_1, "x-amz-checksum-crc32");
}
private void consumeAndVerify(AwsSignedChunkedEncodingInputStream stream, int numChunks, boolean isTrailerChecksum) throws IOException {
ByteArrayOutputStream output = new ByteArrayOutputStream();
IOUtils.copy(stream, output);
String result = new String(output.toByteArray(), StandardCharsets.UTF_8);
assertChunks(result, numChunks, isTrailerChecksum);
}
private void assertChunks(String result, int numExpectedChunks, boolean isTrailerChecksum) {
List<String> lines = Stream.of(result.split(CRLF)).collect(Collectors.toList());
int expectedNumberOfChunks = (2 * numExpectedChunks) - 1 + (isTrailerChecksum ? 2 : 0);
assertThat(lines).hasSize(expectedNumberOfChunks);
for (int i = 0; i < lines.size(); i = i + 2) {
String chunkMetadata = lines.get(i);
boolean isTrailerSignature = isTrailerChecksum && i == lines.size() - 1;
String signatureValue = isTrailerSignature
? chunkMetadata.substring(chunkMetadata.indexOf("x-amz-trailer-signature:")
+ "x-amz-trailer-signature:".length())
: chunkMetadata.substring(chunkMetadata.indexOf(SIGNATURE_KEY) + SIGNATURE_KEY.length());
assertThat(signatureValue.length()).isEqualTo(SIGV4A_SIGNATURE_LENGTH);
}
}
}
| 1,797 |
0 | Create_ds/aws-sdk-java-v2/core/auth-crt/src/test/java/software/amazon/awssdk/authcrt/signer | Create_ds/aws-sdk-java-v2/core/auth-crt/src/test/java/software/amazon/awssdk/authcrt/signer/internal/DefaultAwsCrtS3V4aSignerTest.java | /*
* 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.authcrt.signer.internal;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
import static software.amazon.awssdk.auth.signer.S3SignerExecutionAttribute.ENABLE_CHUNKED_ENCODING;
import static software.amazon.awssdk.auth.signer.S3SignerExecutionAttribute.ENABLE_PAYLOAD_SIGNING;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.Optional;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import software.amazon.awssdk.auth.credentials.AnonymousCredentialsProvider;
import software.amazon.awssdk.auth.credentials.AwsCredentials;
import software.amazon.awssdk.auth.signer.AwsSignerExecutionAttribute;
import software.amazon.awssdk.auth.signer.S3SignerExecutionAttribute;
import software.amazon.awssdk.auth.signer.internal.chunkedencoding.AwsSignedChunkedEncodingInputStream;
import software.amazon.awssdk.auth.signer.internal.util.SignerMethodResolver;
import software.amazon.awssdk.authcrt.signer.AwsCrtV4aSigner;
import software.amazon.awssdk.authcrt.signer.SignerTestUtils;
import software.amazon.awssdk.authcrt.signer.SigningTestCase;
import software.amazon.awssdk.core.checksums.Algorithm;
import software.amazon.awssdk.core.checksums.ChecksumSpecs;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.core.interceptor.SdkInternalExecutionAttribute;
import software.amazon.awssdk.core.interceptor.trait.HttpChecksum;
import software.amazon.awssdk.core.internal.signer.SigningMethod;
import software.amazon.awssdk.crt.auth.signing.AwsSigningConfig;
import software.amazon.awssdk.http.SdkHttpFullRequest;
/**
* Unit tests for the {@link DefaultAwsCrtS3V4aSigner}.
*/
@RunWith(MockitoJUnitRunner.class)
public class DefaultAwsCrtS3V4aSignerTest {
private static HttpChecksum HTTP_CRC32_CHECKSUM =
HttpChecksum.builder().requestAlgorithm("crc32").isRequestStreaming(true).build();
@Mock
AwsCrt4aSigningAdapter signerAdapter;
ArgumentCaptor<AwsSigningConfig> configCaptor = ArgumentCaptor.forClass(AwsSigningConfig.class);
private SigningConfigProvider configProvider;
private DefaultAwsCrtS3V4aSigner s3V4aSigner;
@Before
public void setup() {
configProvider = new SigningConfigProvider();
s3V4aSigner = new DefaultAwsCrtS3V4aSigner(signerAdapter, configProvider);
SdkHttpFullRequest unsignedPayloadSignedRequest = SignerTestUtils.createSignedHttpRequest("data");
SdkHttpFullRequest signedPayloadSignedRequest = SignerTestUtils.createSignedPayloadHttpRequest("data");
String signedPayloadSignature = SignerTestUtils.extractSignatureFromAuthHeader(signedPayloadSignedRequest);
// when(configProvider.createS3CrtSigningConfig(any())).thenReturn(new AwsSigningConfig());
when(signerAdapter.sign(any(), any())).thenReturn(new SdkSigningResult(signedPayloadSignature.getBytes(StandardCharsets.UTF_8),
signedPayloadSignedRequest));
when(signerAdapter.signRequest(any(), any())).thenReturn(unsignedPayloadSignedRequest);
}
@Test
public void when_credentials_are_anonymous_return_request() {
SigningTestCase testCase = SignerTestUtils.createBasicHeaderSigningTestCase();
ExecutionAttributes executionAttributes = SignerTestUtils.buildBasicExecutionAttributes(testCase);
executionAttributes.putAttribute(AwsSignerExecutionAttribute.AWS_CREDENTIALS,
AnonymousCredentialsProvider.create().resolveCredentials());
SdkHttpFullRequest request = testCase.requestBuilder.build();
SdkHttpFullRequest signedRequest = s3V4aSigner.sign(request, executionAttributes);
assertThat(signedRequest).isEqualTo(request);
}
@Test
public void no_special_configuration_does_not_sign_payload() {
SigningTestCase testCase = SignerTestUtils.createBasicHeaderSigningTestCase();
ExecutionAttributes executionAttributes = SignerTestUtils.buildBasicExecutionAttributes(testCase);
SdkHttpFullRequest request = testCase.requestBuilder.build();
SdkHttpFullRequest signedRequest = s3V4aSigner.sign(request, executionAttributes);
verifyUnsignedPayload(signedRequest);
}
@Test
public void protocol_http_triggers_payload_signing() {
SigningTestCase testCase = SignerTestUtils.createBasicHeaderSigningTestCase();
ExecutionAttributes executionAttributes = SignerTestUtils.buildBasicExecutionAttributes(testCase);
SdkHttpFullRequest.Builder requestBuilder = testCase.requestBuilder;
requestBuilder.uri(URI.create("http://demo.us-east-1.amazonaws.com"));
SdkHttpFullRequest signedRequest = s3V4aSigner.sign(requestBuilder.build(), executionAttributes);
verifySignedPayload(signedRequest);
}
@Test
public void protocol_http_triggers_payload_signing_with_trailer_checksums() {
SigningTestCase testCase = SignerTestUtils.createBasicHeaderSigningTestCase();
ExecutionAttributes executionAttributes = SignerTestUtils.buildBasicExecutionAttributes(testCase);
executionAttributes.putAttribute(SdkInternalExecutionAttribute.HTTP_CHECKSUM, HTTP_CRC32_CHECKSUM);
SdkHttpFullRequest.Builder requestBuilder = testCase.requestBuilder;
requestBuilder.uri(URI.create("http://demo.us-east-1.amazonaws.com"));
SdkHttpFullRequest signedRequest = s3V4aSigner.sign(requestBuilder.build(), executionAttributes);
verifySignedChecksumPayload(signedRequest);
}
@Test
public void unsigned_payload_signing_with_trailer_checksums() {
SigningTestCase testCase = SignerTestUtils.createBasicHeaderSigningTestCase();
ExecutionAttributes executionAttributes = SignerTestUtils.buildBasicExecutionAttributes(testCase);
executionAttributes.putAttribute(SdkInternalExecutionAttribute.HTTP_CHECKSUM, HTTP_CRC32_CHECKSUM);
SdkHttpFullRequest request = testCase.requestBuilder.build();
SdkHttpFullRequest signedRequest = s3V4aSigner.sign(request, executionAttributes);
verifyUnsignedPayloadWithTrailerChecksum(signedRequest);
}
@Test
public void payloadSigning_AND_chunkedEnabled_triggers_payload_signing() {
SigningTestCase testCase = SignerTestUtils.createBasicHeaderSigningTestCase();
ExecutionAttributes executionAttributes = SignerTestUtils.buildBasicExecutionAttributes(testCase);
executionAttributes.putAttribute(S3SignerExecutionAttribute.ENABLE_PAYLOAD_SIGNING, true);
executionAttributes.putAttribute(S3SignerExecutionAttribute.ENABLE_CHUNKED_ENCODING, true);
SdkHttpFullRequest signedRequest = s3V4aSigner.sign(testCase.requestBuilder.build(), executionAttributes);
verifySignedPayload(signedRequest);
}
@Test
public void payloadSigning_and_chunked_disabled_does_not_sign_payload() {
SigningTestCase testCase = SignerTestUtils.createBasicHeaderSigningTestCase();
ExecutionAttributes executionAttributes = SignerTestUtils.buildBasicExecutionAttributes(testCase);
executionAttributes.putAttribute(S3SignerExecutionAttribute.ENABLE_PAYLOAD_SIGNING, true);
executionAttributes.putAttribute(S3SignerExecutionAttribute.ENABLE_CHUNKED_ENCODING, false);
SdkHttpFullRequest signedRequest = s3V4aSigner.sign(testCase.requestBuilder.build(), executionAttributes);
verifyUnsignedPayload(signedRequest);
}
@Test
public void no_payloadSigning_and_chunkedEnabled_does_not_sign_payload() {
SigningTestCase testCase = SignerTestUtils.createBasicHeaderSigningTestCase();
ExecutionAttributes executionAttributes = SignerTestUtils.buildBasicExecutionAttributes(testCase);
executionAttributes.putAttribute(S3SignerExecutionAttribute.ENABLE_PAYLOAD_SIGNING, false);
executionAttributes.putAttribute(S3SignerExecutionAttribute.ENABLE_CHUNKED_ENCODING, true);
SdkHttpFullRequest signedRequest = s3V4aSigner.sign(testCase.requestBuilder.build(), executionAttributes);
verifyUnsignedPayload(signedRequest);
}
@Test
public void presigning_returns_signed_params() {
SdkHttpFullRequest signedPresignedRequest = SignerTestUtils.createPresignedPayloadHttpRequest("data");
when(signerAdapter.signRequest(any(), any())).thenReturn(signedPresignedRequest);
SigningTestCase testCase = SignerTestUtils.createBasicQuerySigningTestCase();
ExecutionAttributes executionAttributes = SignerTestUtils.buildBasicExecutionAttributes(testCase);
SdkHttpFullRequest request = testCase.requestBuilder.build();
SdkHttpFullRequest signed = s3V4aSigner.presign(request, executionAttributes);
assertThat(signed.rawQueryParameters().get("X-Amz-Signature").get(0)).isEqualTo("signature");
}
@Test
public void defaultAwsCrtS3V4aSigner_resolves_to_correct_signing_method(){
ExecutionAttributes executionAttributes = Mockito.mock(ExecutionAttributes.class);
AwsCredentials awsCredentials = Mockito.mock(AwsCredentials.class);
when(executionAttributes.getOptionalAttribute(ENABLE_PAYLOAD_SIGNING)).thenReturn(Optional.of(false));
when(executionAttributes.getOptionalAttribute(ENABLE_CHUNKED_ENCODING)).thenReturn(Optional.of(true));
SigningMethod signingMethod = SignerMethodResolver.resolveSigningMethodUsed(DefaultAwsCrtS3V4aSigner.create(),
executionAttributes,
awsCredentials);
assertThat(signingMethod).isEqualTo(SigningMethod.PROTOCOL_STREAMING_SIGNING_AUTH);
}
private void verifyUnsignedPayload(SdkHttpFullRequest signedRequest) {
verifyUnsignedHeaderRequest(signedRequest);
Mockito.verify(signerAdapter).signRequest(any(), configCaptor.capture());
AwsSigningConfig usedConfig = configCaptor.getValue();
assertThat(usedConfig.getSignedBodyValue()).isEqualTo(AwsSigningConfig.AwsSignedBodyValue.UNSIGNED_PAYLOAD);
}
private void verifyUnsignedPayloadWithTrailerChecksum(SdkHttpFullRequest signedRequest) {
verifyUnsignedHeaderRequest(signedRequest);
Mockito.verify(signerAdapter).signRequest(any(), configCaptor.capture());
AwsSigningConfig usedConfig = configCaptor.getValue();
assertThat(usedConfig.getSignedBodyValue()).isEqualTo("STREAMING-UNSIGNED-PAYLOAD-TRAILER");
}
private void verifyUnsignedHeaderRequest(SdkHttpFullRequest signedRequest) {
assertThat(signedRequest.firstMatchingHeader("Authorization")).isPresent();
assertThat(signedRequest.firstMatchingHeader("x-amz-decoded-content-length")).isNotPresent();
assertThat(signedRequest.contentStreamProvider()).isPresent();
assertThat(signedRequest.contentStreamProvider().get().newStream()).isNotInstanceOf(AwsSignedChunkedEncodingInputStream.class);
}
private void verifySignedPayload(SdkHttpFullRequest signedRequest) {
verifySignedRequestHeaders(signedRequest);
verifySignedBody(AwsSigningConfig.AwsSignedBodyValue.STREAMING_AWS4_ECDSA_P256_SHA256_PAYLOAD);
}
private void verifySignedChecksumPayload(SdkHttpFullRequest signedRequest) {
verifySignedRequestHeaders(signedRequest);
verifySignedBody(AwsSigningConfig.AwsSignedBodyValue.STREAMING_AWS4_ECDSA_P256_SHA256_PAYLOAD_TRAILER);
}
private void verifySignedBody(String awsSignedBodyValue) {
Mockito.verify(signerAdapter).sign(any(), configCaptor.capture());
AwsSigningConfig usedConfig = configCaptor.getValue();
assertThat(usedConfig.getSignedBodyValue()).isEqualTo(awsSignedBodyValue);
}
private void verifySignedRequestHeaders(SdkHttpFullRequest signedRequest) {
assertThat(signedRequest.firstMatchingHeader("Authorization")).isPresent();
assertThat(signedRequest.firstMatchingHeader("Content-Length")).isPresent();
assertThat(signedRequest.firstMatchingHeader("x-amz-decoded-content-length")).isPresent();
assertThat(signedRequest.contentStreamProvider()).isPresent();
assertThat(signedRequest.contentStreamProvider().get().newStream()).isInstanceOf(AwsSignedChunkedEncodingInputStream.class);
}
}
| 1,798 |
0 | Create_ds/aws-sdk-java-v2/core/auth-crt/src/test/java/software/amazon/awssdk/authcrt/signer | Create_ds/aws-sdk-java-v2/core/auth-crt/src/test/java/software/amazon/awssdk/authcrt/signer/internal/AwsCrtV4aSignerSigningScopeTest.java | /*
* 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.authcrt.signer.internal;
import software.amazon.awssdk.auth.signer.AwsSignerExecutionAttribute;
import software.amazon.awssdk.authcrt.signer.AwsCrtV4aSigner;
import software.amazon.awssdk.authcrt.signer.SignerTestUtils;
import software.amazon.awssdk.authcrt.signer.SigningTestCase;
import software.amazon.awssdk.core.interceptor.ExecutionAttributes;
import software.amazon.awssdk.http.SdkHttpFullRequest;
import software.amazon.awssdk.regions.RegionScope;
public class AwsCrtV4aSignerSigningScopeTest extends BaseSigningScopeTest {
@Override
protected SdkHttpFullRequest signRequestWithScope(SigningTestCase testCase, RegionScope defaultRegionScope,
RegionScope regionScope) {
ExecutionAttributes executionAttributes = SignerTestUtils.buildBasicExecutionAttributes(testCase);
if (regionScope != null) {
executionAttributes.putAttribute(AwsSignerExecutionAttribute.SIGNING_REGION_SCOPE, regionScope);
}
SdkHttpFullRequest request = testCase.requestBuilder.build();
return AwsCrtV4aSigner.builder().defaultRegionScope(defaultRegionScope).build().sign(request, executionAttributes);
}
@Override
protected SdkHttpFullRequest presignRequestWithScope(SigningTestCase testCase, RegionScope defaultRegionScope,
RegionScope regionScope) {
ExecutionAttributes executionAttributes = SignerTestUtils.buildBasicExecutionAttributes(testCase);
if (regionScope != null) {
executionAttributes.putAttribute(AwsSignerExecutionAttribute.SIGNING_REGION_SCOPE, regionScope);
}
SdkHttpFullRequest request = testCase.requestBuilder.build();
return AwsCrtV4aSigner.builder().defaultRegionScope(defaultRegionScope).build().presign(request, executionAttributes);
}
}
| 1,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.