com.amazonaws.services.securitytoken.AWSSecurityTokenServiceClient Java Examples

The following examples show how to use com.amazonaws.services.securitytoken.AWSSecurityTokenServiceClient. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MockStsOperationsImpl.java    From herd with Apache License 2.0 7 votes vote down vote up
@Override
public AssumeRoleResult assumeRole(AWSSecurityTokenServiceClient awsSecurityTokenServiceClient, AssumeRoleRequest assumeRoleRequest)
{
    assertNotNull(assumeRoleRequest);

    if (assumeRoleRequest.getPolicy() != null && assumeRoleRequest.getPolicy().equals(MockAwsOperationsHelper.AMAZON_THROTTLING_EXCEPTION))
    {
        AmazonServiceException throttlingException = new AmazonServiceException("test throttling exception");
        throttlingException.setErrorCode("ThrottlingException");

        throw throttlingException;
    }

    AssumeRoleResult assumeRoleResult = new AssumeRoleResult();

    assumeRoleResult.setCredentials(new Credentials(MOCK_AWS_ASSUMED_ROLE_ACCESS_KEY, MOCK_AWS_ASSUMED_ROLE_SECRET_KEY, MOCK_AWS_ASSUMED_ROLE_SESSION_TOKEN,
        new Date(System.currentTimeMillis() + 1000 * assumeRoleRequest.getDurationSeconds())));

    return assumeRoleResult;
}
 
Example #2
Source File: AWSClients.java    From aws-codedeploy-plugin with Apache License 2.0 6 votes vote down vote up
private static AWSCredentials getCredentials(String iamRole, String externalId) {
    if (isEmpty(iamRole)) return null;

    AWSSecurityTokenServiceClient sts = new AWSSecurityTokenServiceClient();

    int credsDuration = (int) (AWSCodeDeployPublisher.DEFAULT_TIMEOUT_SECONDS
                    * AWSCodeDeployPublisher.DEFAULT_POLLING_FREQUENCY_SECONDS);

    if (credsDuration > 3600) {
        credsDuration = 3600;
    }

    AssumeRoleResult assumeRoleResult = sts.assumeRole(new AssumeRoleRequest()
                    .withRoleArn(iamRole)
                    .withExternalId(externalId)
                    .withDurationSeconds(credsDuration)
                    .withRoleSessionName(AWSCodeDeployPublisher.ROLE_SESSION_NAME)
    );

    Credentials stsCredentials = assumeRoleResult.getCredentials();
    BasicSessionCredentials credentials = new BasicSessionCredentials(
            stsCredentials.getAccessKeyId(),
            stsCredentials.getSecretAccessKey(),
            stsCredentials.getSessionToken()
    );

    return credentials;
}
 
Example #3
Source File: LambdaCredentialsProvider.java    From service-block-samples with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new session credential that is valid for 12 hours
 *
 * @return an authenticated {@link Credentials} for the new session token
 */
private Credentials getSessionCredentials() {
    // Create a new session with the user credentials for the service instance
    AWSSecurityTokenServiceClient stsClient =
            new AWSSecurityTokenServiceClient(new BasicAWSCredentials(
                    amazonProperties.getAws().getAccessKeyId(),
                    amazonProperties.getAws().getAccessKeySecret()));

    // Start a new session for managing a service instance's bucket
    GetSessionTokenRequest getSessionTokenRequest =
            new GetSessionTokenRequest().withDurationSeconds(43200);

    // Get the session token for the service instance's bucket
    sessionCredentials = stsClient.getSessionToken(getSessionTokenRequest).getCredentials();

    return sessionCredentials;
}
 
Example #4
Source File: CodeBuildBaseCredentials.java    From aws-codebuild-jenkins-plugin with Apache License 2.0 6 votes vote down vote up
@Override
public void refresh() {
    if (!iamRoleArn.isEmpty()) {
        if (!haveCredentialsExpired()) {
            return;
        }

        AWSCredentialsProvider credentialsProvider = getBasicCredentialsOrDefaultChain(accessKey, secretKey);
        AWSCredentials credentials = credentialsProvider.getCredentials();

        AssumeRoleRequest assumeRequest = new AssumeRoleRequest()
                .withRoleArn(iamRoleArn)
                .withExternalId(externalId)
                .withDurationSeconds(3600)
                .withRoleSessionName(ROLE_SESSION_NAME);

        AssumeRoleResult assumeResult = new AWSSecurityTokenServiceClient(credentials).assumeRole(assumeRequest);

        roleCredentials = assumeResult.getCredentials();
    }
}
 
Example #5
Source File: CodeBuildBaseCredentials.java    From aws-codebuild-jenkins-plugin with Apache License 2.0 6 votes vote down vote up
public FormValidation doCheckIamRoleArn(@QueryParameter("proxyHost") final String proxyHost,
                                        @QueryParameter("proxyPort") final String proxyPort,
                                        @QueryParameter("accessKey") final String accessKey,
                                        @QueryParameter("secretKey") final String secretKey,
                                        @QueryParameter("iamRoleArn") final String iamRoleArn,
                                        @QueryParameter("externalId") final String externalId) {

    if (accessKey.isEmpty() || secretKey.isEmpty()) {
        return FormValidation.error("AWS access and secret keys are required to use an IAM role for authorization");
    }

    if(iamRoleArn.isEmpty()) {
        return FormValidation.ok();
    }

    try {

        AWSCredentials initialCredentials = new BasicAWSCredentials(accessKey, secretKey);

        AssumeRoleRequest assumeRequest = new AssumeRoleRequest()
                .withRoleArn(iamRoleArn)
                .withExternalId(externalId)
                .withDurationSeconds(3600)
                .withRoleSessionName(ROLE_SESSION_NAME);

        new AWSSecurityTokenServiceClient(initialCredentials, getClientConfiguration(proxyHost, proxyPort)).assumeRole(assumeRequest);

    } catch (Exception e) {
        String errorMessage = e.getMessage();
        if(errorMessage.length() >= ERROR_MESSAGE_MAX_LENGTH) {
            errorMessage = errorMessage.substring(ERROR_MESSAGE_MAX_LENGTH);
        }
        return FormValidation.error("Authorization failed: " + errorMessage);
    }
    return FormValidation.ok("IAM role authorization successful.");
}
 
Example #6
Source File: StsDaoImpl.java    From herd with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a set of temporary security credentials (consisting of an access key ID, a secret access key, and a security token) that can be used to access
 * the specified AWS resource.
 *
 * @param sessionName the session name that will be associated with the temporary credentials. The session name must be the same for an initial set of
 * credentials and an extended set of credentials if credentials are to be refreshed. The session name also is used to identify the user in AWS logs so it
 * should be something unique and useful to identify the caller/use.
 * @param awsRoleArn the AWS ARN for the role required to provide access to the specified AWS resource
 * @param awsRoleDurationSeconds the duration, in seconds, of the role session. The value can range from 900 seconds (15 minutes) to 3600 seconds (1 hour).
 * @param policy the temporary policy to apply to this request
 *
 * @return the assumed session credentials
 */
@Override
public Credentials getTemporarySecurityCredentials(AwsParamsDto awsParamsDto, String sessionName, String awsRoleArn, int awsRoleDurationSeconds,
    Policy policy)
{
    // Construct a new AWS security token service client using the specified client configuration to access Amazon S3.
    // A credentials provider chain will be used that searches for credentials in this order:
    // - Environment Variables - AWS_ACCESS_KEY_ID and AWS_SECRET_KEY
    // - Java System Properties - aws.accessKeyId and aws.secretKey
    // - Instance Profile Credentials - delivered through the Amazon EC2 metadata service

    ClientConfiguration clientConfiguration = new ClientConfiguration().withRetryPolicy(retryPolicyFactory.getRetryPolicy());

    // Only set the proxy hostname and/or port if they're configured.
    if (StringUtils.isNotBlank(awsParamsDto.getHttpProxyHost()))
    {
        clientConfiguration.setProxyHost(awsParamsDto.getHttpProxyHost());
    }
    if (awsParamsDto.getHttpProxyPort() != null)
    {
        clientConfiguration.setProxyPort(awsParamsDto.getHttpProxyPort());
    }

    AWSSecurityTokenServiceClient awsSecurityTokenServiceClient = new AWSSecurityTokenServiceClient(clientConfiguration);

    // Create the request.
    AssumeRoleRequest assumeRoleRequest = new AssumeRoleRequest();
    assumeRoleRequest.setRoleSessionName(sessionName);
    assumeRoleRequest.setRoleArn(awsRoleArn);
    assumeRoleRequest.setDurationSeconds(awsRoleDurationSeconds);
    if (policy != null)
    {
        assumeRoleRequest.setPolicy(policy.toJson());
    }

    // Get the temporary security credentials.
    AssumeRoleResult assumeRoleResult = stsOperations.assumeRole(awsSecurityTokenServiceClient, assumeRoleRequest);
    return assumeRoleResult.getCredentials();
}
 
Example #7
Source File: MockCloudStore.java    From athenz with Apache License 2.0 6 votes vote down vote up
@Override
AWSSecurityTokenServiceClient getTokenServiceClient() {
    if (exceptionStatusCode != 0) {
        if (amazonException) {
            AmazonServiceException ex = new AmazonServiceException("Error");
            ex.setStatusCode(exceptionStatusCode);
            throw ex;
        } else {
            throw new IllegalArgumentException("Error");
        }
    } else {
        AWSSecurityTokenServiceClient client = Mockito.mock(AWSSecurityTokenServiceClient.class);
        Mockito.when(client.assumeRole(Mockito.any(AssumeRoleRequest.class))).thenReturn(assumeRoleResult);
        Mockito.when(client.getCallerIdentity(Mockito.any(GetCallerIdentityRequest.class))).thenReturn(callerIdentityResult);
        return client;
    }
}
 
Example #8
Source File: AssumeRoleCredentialsStrategy.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
@Override
public AWSCredentialsProvider getDerivedCredentialsProvider(Map<PropertyDescriptor, String> properties,
                                                            AWSCredentialsProvider primaryCredentialsProvider) {
    final String assumeRoleArn = properties.get(ASSUME_ROLE_ARN);
    final String assumeRoleName = properties.get(ASSUME_ROLE_NAME);
    String rawMaxSessionTime = properties.get(MAX_SESSION_TIME);
    rawMaxSessionTime = (rawMaxSessionTime != null) ? rawMaxSessionTime : MAX_SESSION_TIME.getDefaultValue();
    final Integer maxSessionTime = Integer.parseInt(rawMaxSessionTime.trim());
    final String assumeRoleExternalId = properties.get(ASSUME_ROLE_EXTERNAL_ID);
    STSAssumeRoleSessionCredentialsProvider.Builder builder;
    ClientConfiguration config = new ClientConfiguration();

    // If proxy variables are set, then create Client Configuration with those values
    if (proxyVariablesValidForAssumeRole(properties)) {
        final String assumeRoleProxyHost = properties.get(ASSUME_ROLE_PROXY_HOST);
        final Integer assumeRoleProxyPort = Integer.parseInt(properties.get(ASSUME_ROLE_PROXY_PORT));
        config.withProxyHost(assumeRoleProxyHost);
        config.withProxyPort(assumeRoleProxyPort);
    }

    AWSSecurityTokenService securityTokenService = new AWSSecurityTokenServiceClient(primaryCredentialsProvider, config);
    builder = new STSAssumeRoleSessionCredentialsProvider
            .Builder(assumeRoleArn, assumeRoleName)
            .withStsClient(securityTokenService)
            .withRoleSessionDurationSeconds(maxSessionTime);

    if (assumeRoleExternalId != null && !assumeRoleExternalId.isEmpty()) {
        builder = builder.withExternalId(assumeRoleExternalId);
    }

    final AWSCredentialsProvider credsProvider = builder.build();

    return credsProvider;
}
 
Example #9
Source File: AssumeRoleCredentialsStrategy.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Override
public AWSCredentialsProvider getDerivedCredentialsProvider(Map<PropertyDescriptor, String> properties,
                                                            AWSCredentialsProvider primaryCredentialsProvider) {
    final String assumeRoleArn = properties.get(ASSUME_ROLE_ARN);
    final String assumeRoleName = properties.get(ASSUME_ROLE_NAME);
    String rawMaxSessionTime = properties.get(MAX_SESSION_TIME);
    rawMaxSessionTime = (rawMaxSessionTime != null) ? rawMaxSessionTime : MAX_SESSION_TIME.getDefaultValue();
    final Integer maxSessionTime = Integer.parseInt(rawMaxSessionTime.trim());
    final String assumeRoleExternalId = properties.get(ASSUME_ROLE_EXTERNAL_ID);
    STSAssumeRoleSessionCredentialsProvider.Builder builder;
    ClientConfiguration config = new ClientConfiguration();

    // If proxy variables are set, then create Client Configuration with those values
    if (proxyVariablesValidForAssumeRole(properties)) {
        final String assumeRoleProxyHost = properties.get(ASSUME_ROLE_PROXY_HOST);
        final Integer assumeRoleProxyPort = Integer.parseInt(properties.get(ASSUME_ROLE_PROXY_PORT));
        config.withProxyHost(assumeRoleProxyHost);
        config.withProxyPort(assumeRoleProxyPort);
    }

    AWSSecurityTokenService securityTokenService = new AWSSecurityTokenServiceClient(primaryCredentialsProvider, config);
    builder = new STSAssumeRoleSessionCredentialsProvider
            .Builder(assumeRoleArn, assumeRoleName)
            .withStsClient(securityTokenService)
            .withRoleSessionDurationSeconds(maxSessionTime);

    if (assumeRoleExternalId != null && !assumeRoleExternalId.isEmpty()) {
        builder = builder.withExternalId(assumeRoleExternalId);
    }

    final AWSCredentialsProvider credsProvider = builder.build();

    return credsProvider;
}
 
Example #10
Source File: AWSSessionCredentialsFactory.java    From digdag with Apache License 2.0 5 votes vote down vote up
public BasicSessionCredentials get()
{
    AWSCredentials baseCredentials = new BasicAWSCredentials(accessKeyId, secretAccessKey);

    List<Statement> statements = new ArrayList<>();
    acceptableUris.forEach(acceptableUri -> {
                Mode mode = acceptableUri.mode;
                String uri = acceptableUri.uri;
                if (uri.startsWith(URI_S3_PREFIX)) {
                    String s3BucketAndKeyStr = uri.substring(URI_S3_PREFIX.length());
                    String[] s3BucketAndKey = s3BucketAndKeyStr.split("/", 2);
                    statements.add(new Statement(Statement.Effect.Allow)
                            .withActions(S3Actions.ListObjects)
                            .withResources(new Resource("arn:aws:s3:::" + s3BucketAndKey[0])));
                    switch (mode) {
                        case READ:
                            statements.add(new Statement(Statement.Effect.Allow)
                                    .withActions(S3Actions.GetObject)
                                    .withResources(new Resource("arn:aws:s3:::" + s3BucketAndKeyStr + "*")));
                            break;
                        case WRITE:
                            statements.add(new Statement(Statement.Effect.Allow)
                                    .withActions(S3Actions.PutObject)
                                    .withResources(new Resource("arn:aws:s3:::" + s3BucketAndKeyStr + "*")));
                            break;
                    }
                }
                else if (uri.startsWith(URI_DYNAMODB_PREFIX)) {
                    String table = uri.substring(URI_DYNAMODB_PREFIX.length());
                    statements.add(new Statement(Statement.Effect.Allow)
                            .withActions(DynamoDBv2Actions.DescribeTable)
                            .withResources(new Resource(String.format("arn:aws:dynamodb:*:*:table/%s", table))));
                    switch (mode) {
                        case READ:
                            statements.add(new Statement(Statement.Effect.Allow)
                                    .withActions(DynamoDBv2Actions.Scan)
                                    .withResources(new Resource(String.format("arn:aws:dynamodb:*:*:table/%s", table))));
                            break;
                        case WRITE:
                            break;
                    }
                }
                else if (uri.startsWith(URI_EMR_PREFIX)) {
                    String cluster = uri.substring(URI_EMR_PREFIX.length());
                    // TODO: Grant minimum actions
                    statements.add(new Statement(Statement.Effect.Allow)
                                    .withActions(ElasticMapReduceActions.AllElasticMapReduceActions)
                                    .withResources(new Resource(String.format("arn:aws:elasticmapreduce:*:*:cluster/%s", cluster))));
                }
                else {
                    throw new IllegalArgumentException("Unexpected `uri`. uri=" + uri);
                }
            }
    );
    Policy policy = new Policy();
    policy.setStatements(statements);

    Credentials credentials;

    AWSSecurityTokenServiceClient stsClient = new AWSSecurityTokenServiceClient(baseCredentials);

    if (roleArn != null && !roleArn.isEmpty()) {
        // use STS to assume role
        AssumeRoleResult assumeResult = stsClient.assumeRole(new AssumeRoleRequest()
                .withRoleArn(roleArn)
                .withDurationSeconds(durationSeconds)
                .withRoleSessionName(sessionName)
                .withPolicy(policy.toJson()));

        credentials = assumeResult.getCredentials();
    }
    else {
        // Maybe we'd better add an option command later like `without_federated_token`
        GetFederationTokenRequest federationTokenRequest = new GetFederationTokenRequest()
                .withDurationSeconds(durationSeconds)
                .withName(sessionName)
                .withPolicy(policy.toJson());

        GetFederationTokenResult federationTokenResult =
                stsClient.getFederationToken(federationTokenRequest);

        credentials = federationTokenResult.getCredentials();
    }

    return new BasicSessionCredentials(
            credentials.getAccessKeyId(),
            credentials.getSecretAccessKey(),
            credentials.getSessionToken());
}
 
Example #11
Source File: ExamplePlugin.java    From fullstop with Apache License 2.0 5 votes vote down vote up
private AmazonEC2 getClientForAccount(final String accountId, final Region region) {
    final AWSSecurityTokenService stsClient = AWSSecurityTokenServiceClient.builder()
            .withCredentials(new ProfileCredentialsProvider()).build();
    final String roleArn = String.format("arn:aws:iam::%s:role/fullstop-role", accountId);
    final String sessionName = "fullstop-role";
    final AWSCredentialsProvider tempCredentialsProvider = new STSAssumeRoleSessionCredentialsProvider.Builder(roleArn, sessionName)
            .withStsClient(stsClient)
            .withRoleSessionDurationSeconds(3600)
            .build();
    return AmazonEC2Client.builder().withCredentials(tempCredentialsProvider).withRegion(region.getName()).build();
}
 
Example #12
Source File: StsDaoTest.java    From herd with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetTemporarySecurityCredentialsMissingOptionalParameters()
{
    // Create an AWS parameters DTO without proxy settings.
    AwsParamsDto awsParamsDto = new AwsParamsDto();

    // Specify the duration, in seconds, of the role session.
    int awsRoleDurationSeconds = INTEGER_VALUE;

    // Create a retry policy.
    RetryPolicy retryPolicy =
        new RetryPolicy(PredefinedRetryPolicies.DEFAULT_RETRY_CONDITION, PredefinedRetryPolicies.DEFAULT_BACKOFF_STRATEGY, INTEGER_VALUE, true);

    // Create the expected assume role request.
    AssumeRoleRequest assumeRoleRequest =
        new AssumeRoleRequest().withRoleArn(AWS_ROLE_ARN).withRoleSessionName(SESSION_NAME).withDurationSeconds(awsRoleDurationSeconds);

    // Create AWS credentials for API authentication.
    Credentials credentials = new Credentials();
    credentials.setAccessKeyId(AWS_ASSUMED_ROLE_ACCESS_KEY);
    credentials.setSecretAccessKey(AWS_ASSUMED_ROLE_SECRET_KEY);
    credentials.setSessionToken(AWS_ASSUMED_ROLE_SESSION_TOKEN);

    // Create an assume role result.
    AssumeRoleResult assumeRoleResult = new AssumeRoleResult();
    assumeRoleResult.setCredentials(credentials);

    // Mock the external calls.
    when(retryPolicyFactory.getRetryPolicy()).thenReturn(retryPolicy);
    when(stsOperations.assumeRole(any(AWSSecurityTokenServiceClient.class), eq(assumeRoleRequest))).thenReturn(assumeRoleResult);

    // Call the method under test. Please note that we do not specify an IAM policy.
    Credentials result = stsDaoImpl.getTemporarySecurityCredentials(awsParamsDto, SESSION_NAME, AWS_ROLE_ARN, awsRoleDurationSeconds, null);

    // Verify the external calls.
    verify(retryPolicyFactory).getRetryPolicy();
    verify(stsOperations).assumeRole(any(AWSSecurityTokenServiceClient.class), eq(assumeRoleRequest));
    verifyNoMoreInteractionsHelper();

    // Validate the returned object.
    assertEquals(credentials, result);
}
 
Example #13
Source File: StsDaoTest.java    From herd with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetTemporarySecurityCredentials()
{
    // Create an AWS parameters DTO with proxy settings.
    AwsParamsDto awsParamsDto = new AwsParamsDto();
    awsParamsDto.setHttpProxyHost(HTTP_PROXY_HOST);
    awsParamsDto.setHttpProxyPort(HTTP_PROXY_PORT);

    // Specify the duration, in seconds, of the role session.
    int awsRoleDurationSeconds = INTEGER_VALUE;

    // Create an IAM policy.
    Policy policy = new Policy(STRING_VALUE);

    // Create a retry policy.
    RetryPolicy retryPolicy =
        new RetryPolicy(PredefinedRetryPolicies.DEFAULT_RETRY_CONDITION, PredefinedRetryPolicies.DEFAULT_BACKOFF_STRATEGY, INTEGER_VALUE, true);

    // Create the expected assume role request.
    AssumeRoleRequest assumeRoleRequest = new AssumeRoleRequest().withRoleArn(AWS_ROLE_ARN).withRoleSessionName(SESSION_NAME).withPolicy(policy.toJson())
        .withDurationSeconds(awsRoleDurationSeconds);

    // Create AWS credentials for API authentication.
    Credentials credentials = new Credentials();
    credentials.setAccessKeyId(AWS_ASSUMED_ROLE_ACCESS_KEY);
    credentials.setSecretAccessKey(AWS_ASSUMED_ROLE_SECRET_KEY);
    credentials.setSessionToken(AWS_ASSUMED_ROLE_SESSION_TOKEN);

    // Create an assume role result.
    AssumeRoleResult assumeRoleResult = new AssumeRoleResult();
    assumeRoleResult.setCredentials(credentials);

    // Mock the external calls.
    when(retryPolicyFactory.getRetryPolicy()).thenReturn(retryPolicy);
    when(stsOperations.assumeRole(any(AWSSecurityTokenServiceClient.class), eq(assumeRoleRequest))).thenReturn(assumeRoleResult);

    // Call the method under test.
    Credentials result = stsDaoImpl.getTemporarySecurityCredentials(awsParamsDto, SESSION_NAME, AWS_ROLE_ARN, awsRoleDurationSeconds, policy);

    // Verify the external calls.
    verify(retryPolicyFactory).getRetryPolicy();
    verify(stsOperations).assumeRole(any(AWSSecurityTokenServiceClient.class), eq(assumeRoleRequest));
    verifyNoMoreInteractionsHelper();

    // Validate the returned object.
    assertEquals(credentials, result);
}
 
Example #14
Source File: StsOperationsImpl.java    From herd with Apache License 2.0 5 votes vote down vote up
@Override
public AssumeRoleResult assumeRole(AWSSecurityTokenServiceClient awsSecurityTokenServiceClient, AssumeRoleRequest assumeRoleRequest)
{
    return awsSecurityTokenServiceClient.assumeRole(assumeRoleRequest);
}
 
Example #15
Source File: InstanceAWSProviderTest.java    From athenz with Apache License 2.0 5 votes vote down vote up
@Test
public void testVerifyInstanceIdentity() {
    MockInstanceAWSProvider provider = new MockInstanceAWSProvider();
    provider.setIdentitySuper(true);
    AWSSecurityTokenServiceClient mockClient = Mockito.mock(AWSSecurityTokenServiceClient.class);
    GetCallerIdentityResult result = Mockito.mock(GetCallerIdentityResult.class);
    Mockito.when(result.getArn()).thenReturn("arn:aws:sts::1234:assumed-role/athenz.service/athenz.service");
    Mockito.when(mockClient.getCallerIdentity(ArgumentMatchers.any())).thenReturn(result);
    provider.setStsClient(mockClient);
    
    AWSAttestationData info = new AWSAttestationData();
    info.setRole("athenz.service");
    assertTrue(provider.verifyInstanceIdentity(info, "1234"));
}
 
Example #16
Source File: InstanceAWSProviderTest.java    From athenz with Apache License 2.0 5 votes vote down vote up
@Test
public void testVerifyInstanceIdentityARNMismatch() {
    MockInstanceAWSProvider provider = new MockInstanceAWSProvider();
    provider.setIdentitySuper(true);
    AWSSecurityTokenServiceClient mockClient = Mockito.mock(AWSSecurityTokenServiceClient.class);
    GetCallerIdentityResult result = Mockito.mock(GetCallerIdentityResult.class);
    Mockito.when(result.getArn()).thenReturn("arn:aws:sts::1235:assumed-role/athenz.service/athenz.service");
    Mockito.when(mockClient.getCallerIdentity(ArgumentMatchers.any())).thenReturn(result);
    provider.setStsClient(mockClient);
    
    AWSAttestationData info = new AWSAttestationData();
    info.setRole("athenz.service");
    assertFalse(provider.verifyInstanceIdentity(info, "1234"));
}
 
Example #17
Source File: InstanceAWSProviderTest.java    From athenz with Apache License 2.0 5 votes vote down vote up
@Test
public void testVerifyInstanceIdentityException() {
    MockInstanceAWSProvider provider = new MockInstanceAWSProvider();
    provider.setIdentitySuper(true);
    AWSSecurityTokenServiceClient mockClient = Mockito.mock(AWSSecurityTokenServiceClient.class);
    Mockito.when(mockClient.getCallerIdentity(ArgumentMatchers.any()))
            .thenThrow(new ResourceException(101, "invaliderror"));
    provider.setStsClient(mockClient);
    
    AWSAttestationData info = new AWSAttestationData();
    assertFalse(provider.verifyInstanceIdentity(info, "1234"));
}
 
Example #18
Source File: InstanceAWSProviderTest.java    From athenz with Apache License 2.0 5 votes vote down vote up
@Test
public void testVerifyInstanceIdentityNullIdentity() {
    MockInstanceAWSProvider provider = new MockInstanceAWSProvider();
    provider.setIdentitySuper(true);
    AWSSecurityTokenServiceClient mockClient = Mockito.mock(AWSSecurityTokenServiceClient.class);
    Mockito.when(mockClient.getCallerIdentity(ArgumentMatchers.any())).thenReturn(null);
    provider.setStsClient(mockClient);
    
    AWSAttestationData info = new AWSAttestationData();
    assertFalse(provider.verifyInstanceIdentity(info, "1234"));
}
 
Example #19
Source File: AmazonS3Template.java    From spring-boot-starter-amazon-s3 with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new session credential that is valid for 12 hours
 *
 * @return an authenticated {@link Credentials} for the new session token
 */
private Credentials getSessionCredentials() {
    // Create a new session with the user credentials for the service instance
    AWSSecurityTokenServiceClient stsClient =
            new AWSSecurityTokenServiceClient(new BasicAWSCredentials(accessKeyId, accessKeySecret));

    // Start a new session for managing a service instance's bucket
    GetSessionTokenRequest getSessionTokenRequest =
            new GetSessionTokenRequest().withDurationSeconds(43200);

    // Get the session token for the service instance's bucket
    sessionCredentials = stsClient.getSessionToken(getSessionTokenRequest).getCredentials();

    return sessionCredentials;
}
 
Example #20
Source File: AwsSessionService.java    From Gatekeeper with Apache License 2.0 5 votes vote down vote up
@Autowired
public AwsSessionService(AccountInformationService accountInformationService,
                         AWSSecurityTokenServiceClient awsSecurityTokenServiceClient,
                         AwsSessionFactory awsSessionFactory,
                         GatekeeperAwsProperties awsProperties) {

    this.accountInformationService = accountInformationService;
    this.awsSecurityTokenServiceClient = awsSecurityTokenServiceClient;
    this.awsSessionFactory = awsSessionFactory;
    this.sessionTimeout = awsProperties.getSessionTimeout();
    this.sessionTimeoutPad = awsProperties.getSessionTimeoutPad();
    this.roleToAssume = awsProperties.getRoleToAssume();

}
 
Example #21
Source File: AwsSessionService.java    From Gatekeeper with Apache License 2.0 5 votes vote down vote up
@Autowired
public AwsSessionService(AccountInformationService accountInformationService,
                                           AWSSecurityTokenServiceClient awsSecurityTokenServiceClient,
                                           AwsSessionFactory awsSessionFactory,
                                           GatekeeperAwsProperties gatekeeperAwsProperties){
    this.accountInformationService = accountInformationService;
    this.awsSecurityTokenServiceClient = awsSecurityTokenServiceClient;
    this.awsSessionFactory = awsSessionFactory;
    this.gatekeeperAwsProperties = gatekeeperAwsProperties;
}
 
Example #22
Source File: TestPrestoS3FileSystem.java    From presto with Apache License 2.0 5 votes vote down vote up
private static AWSCredentialsProvider getStsCredentialsProvider(PrestoS3FileSystem fs, String expectedRole)
{
    AWSCredentialsProvider awsCredentialsProvider = getAwsCredentialsProvider(fs);
    assertInstanceOf(awsCredentialsProvider, STSAssumeRoleSessionCredentialsProvider.class);

    assertEquals(getFieldValue(awsCredentialsProvider, "roleArn", String.class), expectedRole);

    AWSSecurityTokenService tokenService = getFieldValue(awsCredentialsProvider, "securityTokenService", AWSSecurityTokenService.class);
    assertInstanceOf(tokenService, AWSSecurityTokenServiceClient.class);
    return getFieldValue(tokenService, "awsCredentialsProvider", AWSCredentialsProvider.class);
}
 
Example #23
Source File: ConstructUrlFederatedUsers.java    From aws-doc-sdk-examples with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) {

        /* Calls to AWS STS API operations must be signed using the access key ID 
           and secret access key of an IAM user or using existing temporary 
           credentials. The credentials should not be embedded in code. For 
           this example, the code looks for the credentials in a 
           standard configuration file.
        */
        AWSCredentials credentials = 
          new PropertiesCredentials(
                 AwsConsoleApp.class.getResourceAsStream("AwsCredentials.properties"));
        
        AWSSecurityTokenServiceClient stsClient = 
          new AWSSecurityTokenServiceClient(credentials);
        
        GetFederationTokenRequest getFederationTokenRequest = 
          new GetFederationTokenRequest();
        getFederationTokenRequest.setDurationSeconds(1800);
        getFederationTokenRequest.setName("UserName");
        
        // A sample policy for accessing Amazon Simple Notification Service (Amazon SNS) in the console.
        
        String policy = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Action\":\"sns:*\"," +
          "\"Effect\":\"Allow\",\"Resource\":\"*\"}]}";
        
        getFederationTokenRequest.setPolicy(policy);
        
        GetFederationTokenResult federationTokenResult = 
          stsClient.getFederationToken(getFederationTokenRequest);
        
        Credentials federatedCredentials = federationTokenResult.getCredentials();
        
        // The issuer parameter specifies your internal sign-in
        // page, for example https://mysignin.internal.mycompany.com/.
        // The console parameter specifies the URL to the destination console of the
        // AWS Management Console. This example goes to Amazon SNS. 
        // The signin parameter is the URL to send the request to.
        
        String issuerURL = "https://mysignin.internal.mycompany.com/";
        String consoleURL = "https://console.aws.amazon.com/sns";
        String signInURL = "https://signin.aws.amazon.com/federation";
          
        // Create the sign-in token using temporary credentials,
        // including the access key ID,  secret access key, and security token.
        String sessionJson = String.format(
          "{\"%1$s\":\"%2$s\",\"%3$s\":\"%4$s\",\"%5$s\":\"%6$s\"}",
          "sessionId", federatedCredentials.getAccessKeyId(),
          "sessionKey", federatedCredentials.getSecretAccessKey(),
          "sessionToken", federatedCredentials.getSessionToken());
                      
        // Construct the sign-in request with the request sign-in token action, a
        // 12-hour console session duration, and the JSON document with temporary 
        // credentials as parameters.
        
        String getSigninTokenURL = signInURL + 
                                   "?Action=getSigninToken" +
                                   "&DurationSeconds=43200" + 
                                   "&SessionType=json&Session=" + 
                                   URLEncoder.encode(sessionJson,"UTF-8");
        
        URL url = new URL(getSigninTokenURL);
        
        // Send the request to the AWS federation endpoint to get the sign-in token
        URLConnection conn = url.openConnection ();
        
        BufferedReader bufferReader = new BufferedReader(new 
          InputStreamReader(conn.getInputStream()));  
        String returnContent = bufferReader.readLine();
        
        String signinToken = new JSONObject(returnContent).getString("SigninToken");
        
        String signinTokenParameter = "&SigninToken=" + URLEncoder.encode(signinToken,"UTF-8");
        
        // The issuer parameter is optional, but recommended. Use it to direct users
        // to your sign-in page when their session expires.
        
        String issuerParameter = "&Issuer=" + URLEncoder.encode(issuerURL, "UTF-8");
        
        // Finally, present the completed URL for the AWS console session to the user
        
        String destinationParameter = "&Destination=" + URLEncoder.encode(consoleURL,"UTF-8");
        String loginURL = signInURL + "?Action=login" +
                             signinTokenParameter + issuerParameter + destinationParameter;
    }
 
Example #24
Source File: GatekeeperCommonConfig.java    From Gatekeeper with Apache License 2.0 4 votes vote down vote up
@Bean
public AWSSecurityTokenServiceClient awsSecurityTokenServiceClient() {
    return new AWSSecurityTokenServiceClient(clientConfiguration());
}
 
Example #25
Source File: AwsClient.java    From cloudbreak with Apache License 2.0 4 votes vote down vote up
public AWSSecurityTokenService createAwsSecurityTokenService(AwsCredentialView awsCredential) {
    return isRoleAssumeRequired(awsCredential)
            ? new AWSSecurityTokenServiceClient(createAwsSessionCredentialProvider(awsCredential))
            : new AWSSecurityTokenServiceClient(createAwsCredentials(awsCredential));
}
 
Example #26
Source File: TemporaryCredentialManagement.java    From reinvent2013-mobile-photo-share with Apache License 2.0 4 votes vote down vote up
public TemporaryCredentialManagement() {
    BasicAWSCredentials creds = new BasicAWSCredentials(Configuration.AWS_ACCESS_KEY_ID,
            Configuration.AWS_SECRET_KEY);
    sts = new AWSSecurityTokenServiceClient(creds);
}
 
Example #27
Source File: TemporaryCredentialManagement.java    From reinvent2013-mobile-photo-share with Apache License 2.0 4 votes vote down vote up
public TemporaryCredentialManagement() {
    BasicAWSCredentials creds = new BasicAWSCredentials(Configuration.AWS_ACCESS_KEY_ID,
            Configuration.AWS_SECRET_KEY);
    sts = new AWSSecurityTokenServiceClient(creds);
}
 
Example #28
Source File: StsOperations.java    From herd with Apache License 2.0 3 votes vote down vote up
/**
 * Returns a set of temporary security credentials (consisting of an access key ID, a secret access key, and a security token) that can be used to access
 * the specified AWS resource.
 *
 * @param awsSecurityTokenServiceClient the client for accessing the AWS Security Token Service
 * @param assumeRoleRequest the assume role request
 *
 * @return the response from the AssumeRole service method, as returned by AWS Security Token Service
 */
public AssumeRoleResult assumeRole(AWSSecurityTokenServiceClient awsSecurityTokenServiceClient, AssumeRoleRequest assumeRoleRequest);