com.amazonaws.services.securitytoken.model.Credentials Java Examples

The following examples show how to use com.amazonaws.services.securitytoken.model.Credentials. 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: ConvertService.java    From alexa-meets-polly with Apache License 2.0 7 votes vote down vote up
public static AmazonS3 getS3Client(final String region, final String roleArn) {
    final Regions awsRegion = StringUtils.isNullOrEmpty(region) ? Regions.US_EAST_1 : Regions.fromName(region);

    if (StringUtils.isNullOrEmpty(roleArn)) {
        return AmazonS3ClientBuilder.standard().withRegion(awsRegion).build();
    } else {
        final AssumeRoleRequest assumeRole = new AssumeRoleRequest().withRoleArn(roleArn).withRoleSessionName("io-klerch-mp3-converter");

        final AWSSecurityTokenService sts = AWSSecurityTokenServiceClientBuilder.standard().withRegion(awsRegion).build();
        final Credentials credentials = sts.assumeRole(assumeRole).getCredentials();

        final BasicSessionCredentials sessionCredentials = new BasicSessionCredentials(
                credentials.getAccessKeyId(),
                credentials.getSecretAccessKey(),
                credentials.getSessionToken());

        return AmazonS3ClientBuilder.standard().withRegion(awsRegion).withCredentials(new AWSStaticCredentialsProvider(sessionCredentials)).build();
    }
}
 
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: 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 #5
Source File: StorageHelper.java    From herd with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a new {@link S3FileTransferRequestParamsDto} with temporary credentials as per specified AWS role and session name.
 *
 * @param roleArn the ARN of the role
 * @param sessionName the session name
 *
 * @return the {@link S3FileTransferRequestParamsDto} object
 */
public S3FileTransferRequestParamsDto getS3FileTransferRequestParamsDtoByRole(String roleArn, String sessionName)
{
    // Get the S3 file transfer request parameters DTO with proxy host and port populated from the configuration.
    S3FileTransferRequestParamsDto params = getS3FileTransferRequestParamsDto();

    // Assume the specified role. Set the duration of the role session to 3600 seconds (1 hour).
    Credentials credentials = stsDao.getTemporarySecurityCredentials(params, sessionName, roleArn, 3600, null);

    // Update the AWS parameters DTO with the temporary credentials.
    params.setAwsAccessKeyId(credentials.getAccessKeyId());
    params.setAwsSecretKey(credentials.getSecretAccessKey());
    params.setSessionToken(credentials.getSessionToken());

    return params;
}
 
Example #6
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 #7
Source File: CloudStoreTest.java    From athenz with Apache License 2.0 6 votes vote down vote up
@Test
public void testAssumeAWSRole() {
    MockCloudStore cloudStore = new MockCloudStore();
    cloudStore.awsEnabled = true;
    AssumeRoleResult mockResult = Mockito.mock(AssumeRoleResult.class);
    Credentials creds = Mockito.mock(Credentials.class);
    Mockito.when(creds.getAccessKeyId()).thenReturn("accesskeyid");
    Mockito.when(creds.getSecretAccessKey()).thenReturn("secretaccesskey");
    Mockito.when(creds.getSessionToken()).thenReturn("sessiontoken");
    Mockito.when(creds.getExpiration()).thenReturn(new Date());
    Mockito.when(mockResult.getCredentials()).thenReturn(creds);
    cloudStore.setAssumeRoleResult(mockResult);
    cloudStore.setReturnSuperAWSRole(true);

    AWSTemporaryCredentials awsCreds = cloudStore.assumeAWSRole("account", "syncer", "athenz.syncer", null, null);
    assertNotNull(awsCreds);
    assertEquals(awsCreds.getAccessKeyId(), "accesskeyid");
    assertEquals(awsCreds.getSessionToken(), "sessiontoken");
    assertEquals(awsCreds.getSecretAccessKey(), "secretaccesskey");
    cloudStore.close();
}
 
Example #8
Source File: AwsSessionCredentialClient.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
public AwsSessionCredentials retrieveSessionCredentials(AwsCredentialView awsCredential) {
    String externalId = awsCredential.getExternalId();
    AssumeRoleRequest assumeRoleRequest = new AssumeRoleRequest()
            .withDurationSeconds(DEFAULT_SESSION_CREDENTIALS_DURATION)
            .withExternalId(StringUtils.isEmpty(externalId) ? deprecatedExternalId : externalId)
            .withRoleArn(awsCredential.getRoleArn())
            .withRoleSessionName(roleSessionName);
    LOGGER.debug("Trying to assume role with role arn {}", awsCredential.getRoleArn());
    try {
        AssumeRoleResult result = awsSecurityTokenServiceClient(awsCredential).assumeRole(assumeRoleRequest);
        Credentials credentialsResponse = result.getCredentials();

        String formattedExpirationDate = "";
        Date expirationTime = credentialsResponse.getExpiration();
        if (expirationTime != null) {
            formattedExpirationDate = new StdDateFormat().format(expirationTime);
        }
        LOGGER.debug("Assume role result credential: role arn: {}, expiration date: {}",
                awsCredential.getRoleArn(), formattedExpirationDate);

        return new AwsSessionCredentials(
                credentialsResponse.getAccessKeyId(),
                credentialsResponse.getSecretAccessKey(),
                credentialsResponse.getSessionToken(),
                credentialsResponse.getExpiration());
    } catch (SdkClientException e) {
        LOGGER.error("Unable to assume role. Check exception for details.", e);
        throw e;
    }
}
 
Example #9
Source File: ZTSClient.java    From athenz with Apache License 2.0 6 votes vote down vote up
Credentials assumeAWSRole(String account, String roleName) {
    
    try {
        AssumeRoleRequest req = getAssumeRoleRequest(account, roleName);
        return AWSSecurityTokenServiceClientBuilder.defaultClient().assumeRole(req).getCredentials();
    } catch (Exception ex) {
        LOG.error("assumeAWSRole - unable to assume role: {}", ex.getMessage());
        return null;
    }
}
 
Example #10
Source File: ZTSClient.java    From athenz with Apache License 2.0 6 votes vote down vote up
String getAWSLambdaAttestationData(final String athenzService, final String account) {
    
    AWSAttestationData data = new AWSAttestationData();
    data.setRole(athenzService);
    
    Credentials awsCreds = assumeAWSRole(account, athenzService);
    data.setAccess(awsCreds.getAccessKeyId());
    data.setSecret(awsCreds.getSecretAccessKey());
    data.setToken(awsCreds.getSessionToken());
    
    ObjectMapper mapper = new ObjectMapper();
    String jsonData = null;
    try {
        jsonData = mapper.writeValueAsString(data);
    } catch (JsonProcessingException ex) {
        LOG.error("Unable to generate attestation json data: {}", ex.getMessage());
    }
    
    return jsonData;
}
 
Example #11
Source File: WithAWSStep.java    From pipeline-aws-plugin with Apache License 2.0 6 votes vote down vote up
private void withFederatedUserId(@Nonnull EnvVars localEnv) {
	if (!StringUtils.isNullOrEmpty(this.step.getFederatedUserId())) {
		AWSSecurityTokenService sts = AWSClientFactory.create(AWSSecurityTokenServiceClientBuilder.standard(), this.envVars);
		GetFederationTokenRequest getFederationTokenRequest = new GetFederationTokenRequest();
		getFederationTokenRequest.setDurationSeconds(this.step.getDuration());
		getFederationTokenRequest.setName(this.step.getFederatedUserId());
		getFederationTokenRequest.setPolicy(ALLOW_ALL_POLICY);

		GetFederationTokenResult federationTokenResult = sts.getFederationToken(getFederationTokenRequest);

		Credentials credentials = federationTokenResult.getCredentials();
		localEnv.override(AWSClientFactory.AWS_ACCESS_KEY_ID, credentials.getAccessKeyId());
		localEnv.override(AWSClientFactory.AWS_SECRET_ACCESS_KEY, credentials.getSecretAccessKey());
		localEnv.override(AWSClientFactory.AWS_SESSION_TOKEN, credentials.getSessionToken());
		this.envVars.overrideAll(localEnv);
	}

}
 
Example #12
Source File: IdentityTokenVendingMachine.java    From reinvent2013-mobile-photo-share with Apache License 2.0 6 votes vote down vote up
/**
 * Generate tokens for given UID. The tokens are encrypted using the key
 * corresponding to UID. Encrypted tokens are then wrapped in JSON object
 * before returning it. Useful in Anonymous and Identity modes
 * 
 * @param uid
 *            Unique device identifier
 * @return encrypted tokens as JSON object
 * @throws DataAccessException
 * @throws UnauthorizedException
 */
public String getToken(String uid) throws DataAccessException, UnauthorizedException {
    DeviceInfo device = deviceAuthenticator.getDeviceInfo(uid);
    if (device == null) {
        throw new UnauthorizedException("Couldn't find device: " + uid);
    }

    UserInfo user = userAuthenticator.getUserInfo(device.getUsername());
    if (user == null) {
        throw new UnauthorizedException("Couldn't find user: " + device.getUsername());
    }

    log.info("Creating temporary credentials");
    Credentials sessionCredentials = credentialManagement.getTemporaryCredentials(user.getUsername());

    log.info("Generating session tokens for UID : " + uid);
    return Utilities.prepareJsonResponseForTokens(sessionCredentials, device.getKey());
}
 
Example #13
Source File: AnonymousTokenVendingMachine.java    From reinvent2013-mobile-photo-share with Apache License 2.0 5 votes vote down vote up
/**
 * Generate tokens for given UID. The tokens are encrypted using the key
 * corresponding to UID. Encrypted tokens are then wrapped in JSON object
 * before returning it. Useful in Anonymous and Identity modes
 * 
 * @param uid
 *            Unique device identifier
 * @return encrypted tokens as JSON object
 * @throws DataAccessException
 * @throws UnauthorizedException
 */
public String getToken(String uid) throws DataAccessException, UnauthorizedException {
    DeviceInfo device = authenticator.getDeviceInfo(uid);
    if (device == null) {
        throw new UnauthorizedException("Couldn't find device: " + uid);
    }

    log.info("Creating temporary credentials");
    Credentials sessionCredentials = credentialManagement.getTemporaryCredentials(uid);

    log.info("Generating session tokens for UID : " + uid);
    return Utilities.prepareJsonResponseForTokens(sessionCredentials, device.getKey());
}
 
Example #14
Source File: TemporaryCredentialManagement.java    From reinvent2013-mobile-photo-share with Apache License 2.0 5 votes vote down vote up
/**
 * Retrieves temporary credentials for the given user.
 * 
 * @param username
 *            a given user name
 * @return temporary AWS credentials
 * @throws DataAccessException
 *             When it fails to get federation token from STS
 */
public Credentials getTemporaryCredentials(String username) throws DataAccessException {
    GetFederationTokenRequest getFederationTokenRequest = new GetFederationTokenRequest();
    getFederationTokenRequest.setName(username);
    getFederationTokenRequest.setPolicy(getPolicyObject());
    getFederationTokenRequest.setDurationSeconds(new Integer(Configuration.SESSION_DURATION));

    try {
        return sts.getFederationToken(getFederationTokenRequest).getCredentials();
    } catch (AmazonClientException e) {
        throw new DataAccessException("Failed to get federation token for user: " + username, e);
    }
}
 
Example #15
Source File: TemporaryCredentialManagement.java    From reinvent2013-mobile-photo-share with Apache License 2.0 5 votes vote down vote up
/**
 * Retrieves temporary credentials for the given user.
 * 
 * @param username
 *            a given user name
 * @return temporary AWS credentials
 * @throws DataAccessException
 *             When it fails to get federation token from STS
 */
public Credentials getTemporaryCredentials(String username) throws DataAccessException {
    GetFederationTokenRequest getFederationTokenRequest = new GetFederationTokenRequest();
    getFederationTokenRequest.setName(username);
    getFederationTokenRequest.setPolicy(getPolicyObject(username));
    getFederationTokenRequest.setDurationSeconds(new Integer(Configuration.SESSION_DURATION));

    try {
        return sts.getFederationToken(getFederationTokenRequest).getCredentials();
    } catch (AmazonClientException e) {
        throw new DataAccessException("Failed to get federation token for user: " + username, e);
    }
}
 
Example #16
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 #17
Source File: AwsSessionServiceTest.java    From Gatekeeper with Apache License 2.0 5 votes vote down vote up
@Before
public void before() {
    awsEnvironment = new AWSEnvironment("Dev", "us-west-2");
    Mockito.when(gatekeeperAwsProperties.getSessionTimeout()).thenReturn(900000);
    Mockito.when(gatekeeperAwsProperties.getSessionTimeoutPad()).thenReturn(60000);

    List<Region> regions = new ArrayList<>();
    Region testRegion1 = new Region();
    Region testRegion2 = new Region();
    testRegion1.setName("us-west-2");
    testRegion2.setName("us-east-1");
    regions.add(testRegion1);
    regions.add(testRegion2);
    Account fakeAccount = new Account();
    fakeAccount.setAccountId("123");
    fakeAccount.setAlias("hello");
    fakeAccount.setRegions(regions);
    fakeAccount.setSdlc("Test");
    fakeAccount.setName("Test Account");

    AssumeRoleResult fakeRoleResult = new AssumeRoleResult();
    Credentials fakeFreshCredentials = new Credentials();   // ( ͡° ͜ʖ ͡°)
    fakeFreshCredentials.setAccessKeyId("testing");
    fakeFreshCredentials.setSecretAccessKey("s3cr3t");
    fakeFreshCredentials.setSessionToken("s35510nt0k3n");
    fakeRoleResult.setCredentials(fakeFreshCredentials);
    when(accountInformationService.getAccountByAlias("Dev")).thenReturn(fakeAccount);
    when(awsSecurityTokenServiceClient.assumeRole(any())).thenReturn(fakeRoleResult);
    when(awsSessionFactory.createEc2Session(any(), any())).thenReturn(amazonEC2Client);
    when(awsSessionFactory.createSsmSession(any(), any())).thenReturn(awsSimpleSystemsManagementClient);


}
 
Example #18
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 #19
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 #20
Source File: Utilities.java    From reinvent2013-mobile-photo-share with Apache License 2.0 5 votes vote down vote up
public static String prepareJsonResponseForTokens(Credentials sessionCredentials, String key) {

        StringBuilder responseBody = new StringBuilder();
        responseBody.append("{");
        responseBody.append("\taccessKey: \"").append(sessionCredentials.getAccessKeyId()).append("\",");
        responseBody.append("\tsecretKey: \"").append(sessionCredentials.getSecretAccessKey()).append("\",");
        responseBody.append("\tsecurityToken: \"").append(sessionCredentials.getSessionToken()).append("\",");
        responseBody.append("\texpirationDate: \"").append(sessionCredentials.getExpiration().getTime()).append("\"");
        responseBody.append("}");

        // Encrypting the response
        return AESEncryption.wrap(responseBody.toString(), key);
    }
 
Example #21
Source File: EmrHelper.java    From herd with Apache License 2.0 5 votes vote down vote up
private void updateAwsParamsForCrossAccountAccess(AwsParamsDto awsParamsDto, String accountId)
{
    // Retrieve the role ARN and make sure it exists.
    TrustingAccountEntity trustingAccountEntity = trustingAccountDaoHelper.getTrustingAccountEntity(accountId.trim());
    String roleArn = trustingAccountEntity.getRoleArn();

    // Assume the role. Set the duration of the role session to 3600 seconds (1 hour).
    Credentials credentials = stsDao.getTemporarySecurityCredentials(awsParamsDto, UUID.randomUUID().toString(), roleArn, 3600, null);

    // Update the AWS parameters DTO with the temporary credentials.
    awsParamsDto.setAwsAccessKeyId(credentials.getAccessKeyId());
    awsParamsDto.setAwsSecretKey(credentials.getSecretAccessKey());
    awsParamsDto.setSessionToken(credentials.getSessionToken());
}
 
Example #22
Source File: ProfileCredentialProvider.java    From strongbox with Apache License 2.0 5 votes vote down vote up
/**
 * Resolve AWS credentials based on MFA/Assume role
 *
 * We will assume that if mfa_serial is defined, then role_arn and source_profile also has to be specified.
 *
 * Please note that Strongbox differ from the AWS CLI in the following:
 * AWS CLI: 'Note that configuration variables for using IAM roles can only be in the AWS CLI config file.'
 * Strongbox: '--assume-role' can be specified explicitly
 *
 * https://docs.aws.amazon.com/cli/latest/topic/config-vars.html#using-aws-iam-roles
 */
private AWSCredentials assumeRole(ClientConfiguration clientConfiguration,
                                  ConfigProviderChain configProvider,
                                  ProfileIdentifier profile,
                                  RoleARN roleToAssume) {

    Optional<ProfileIdentifier> sourceProfile = configProvider.getSourceProfile(profile);
    if (!sourceProfile.isPresent()) {
        throw new IllegalStateException(String.format("'%s' must be specified when using '%s' for profile '%s'",
                AWSConfigPropertyKey.SOURCE_PROFILE,
                AWSConfigPropertyKey.ROLE_ARN,
                profile.name));
    }

    SessionCache sessionCache = new SessionCache(profile, roleToAssume);
    Optional<BasicSessionCredentials> cachedCredentials = sessionCache.load();

    if (cachedCredentials.isPresent()) {
        return cachedCredentials.get();
    } else {
        AWSCredentialsProvider staticCredentialsProvider = new AWSStaticCredentialsProvider(getStaticCredentials(configProvider, sourceProfile.get()));

        AWSSecurityTokenService client = AWSSecurityTokenServiceClientBuilder.standard()
                .withCredentials(staticCredentialsProvider)
                .withClientConfiguration(transformAndVerifyOrThrow(clientConfiguration))
                .withRegion(RegionResolver.getRegion())
                .build();

        String sessionId = String.format("strongbox-cli-session-%s", ZonedDateTime.now().toEpochSecond());

        AssumeRoleRequest request = new AssumeRoleRequest();
        request.withRoleArn(roleToAssume.toArn())
                .withRoleSessionName(sessionId);

        Optional<String> mfaSerial = configProvider.getMFASerial(profile);
        if (mfaSerial.isPresent()) {
            MFAToken mfaToken = mfaTokenSupplier.get();

            request.withSerialNumber(mfaSerial.get())
                    .withTokenCode(mfaToken.value);
        }

        AssumeRoleResult result = client.assumeRole(request);
        Credentials credentials = result.getCredentials();

        BasicSessionCredentials basicSessionCredentials = new BasicSessionCredentials(credentials.getAccessKeyId(), credentials.getSecretAccessKey(), credentials.getSessionToken());

        sessionCache.save(result.getAssumedRoleUser(),
                basicSessionCredentials,
                ZonedDateTime.ofInstant(credentials.getExpiration().toInstant(), ZoneId.of("UTC")));

        return basicSessionCredentials;
    }
}
 
Example #23
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 #24
Source File: ZTSClientMock.java    From athenz with Apache License 2.0 5 votes vote down vote up
@Override
Credentials assumeAWSRole(String account, String roleName) {
    
    Credentials creds = new Credentials();
    creds.setAccessKeyId("access");
    creds.setSecretAccessKey("secret");
    creds.setSessionToken("token");
    return creds;
}
 
Example #25
Source File: CloudStoreTest.java    From athenz with Apache License 2.0 5 votes vote down vote up
@Test
public void testAssumeAWSRoleFailedCreds() {
    MockCloudStore cloudStore = new MockCloudStore();
    cloudStore.awsEnabled = true;
    AssumeRoleResult mockResult = Mockito.mock(AssumeRoleResult.class);
    Credentials creds = Mockito.mock(Credentials.class);
    Mockito.when(creds.getAccessKeyId()).thenReturn("accesskeyid");
    Mockito.when(creds.getSecretAccessKey()).thenReturn("secretaccesskey");
    Mockito.when(creds.getSessionToken()).thenReturn("sessiontoken");
    Mockito.when(creds.getExpiration()).thenReturn(new Date());
    Mockito.when(mockResult.getCredentials()).thenReturn(creds);
    cloudStore.setAssumeRoleResult(mockResult);
    cloudStore.setReturnSuperAWSRole(true);

    // add our key to the invalid cache

    cloudStore.putInvalidCacheCreds(cloudStore.getCacheKey("account", "syncer", "athenz.syncer", null, null));
    assertNull(cloudStore.assumeAWSRole("account", "syncer", "athenz.syncer", null, null));
    assertNull(cloudStore.assumeAWSRole("account", "syncer", "athenz.syncer", null, null));

    // now set the timeout to 1 second and sleep that long and after
    // that our test case should work as before

    cloudStore.invalidCacheTimeout = 1;
    try {
        Thread.sleep(1000);
    } catch (InterruptedException ignored) {
    }
    assertNotNull(cloudStore.assumeAWSRole("account", "syncer", "athenz.syncer", null, null));
    cloudStore.close();
}
 
Example #26
Source File: UploadDownloadServiceImpl.java    From herd with Apache License 2.0 4 votes vote down vote up
@NamespacePermission(fields = "#namespace", permissions = NamespacePermissionEnum.WRITE)
@Override
public UploadSingleCredentialExtensionResponse extendUploadSingleCredentials(String namespace, String businessObjectDefinitionName,
    String businessObjectFormatUsage, String businessObjectFormatFileType, Integer businessObjectFormatVersion, String partitionValue,
    Integer businessObjectDataVersion)
{
    // Create the business object data key.
    BusinessObjectDataKey businessObjectDataKey =
        new BusinessObjectDataKey(namespace, businessObjectDefinitionName, businessObjectFormatUsage, businessObjectFormatFileType,
            businessObjectFormatVersion, partitionValue, null, businessObjectDataVersion);

    // Validate and trim the business object data key.
    businessObjectDataHelper.validateBusinessObjectDataKey(businessObjectDataKey, true, true);

    // Get the business object data for the key.
    BusinessObjectDataEntity businessObjectDataEntity = businessObjectDataDaoHelper.getBusinessObjectDataEntity(businessObjectDataKey);

    // Ensure the status of the business object data is "uploading" in order to extend credentials.
    if (!(businessObjectDataEntity.getStatus().getCode().equals(BusinessObjectDataStatusEntity.UPLOADING)))
    {
        throw new IllegalArgumentException(String.format(String
            .format("Business object data {%s} has a status of \"%s\" and must be \"%s\" to extend " + "credentials.",
                businessObjectDataHelper.businessObjectDataKeyToString(businessObjectDataKey), businessObjectDataEntity.getStatus().getCode(),
                BusinessObjectDataStatusEntity.UPLOADING)));
    }

    // Get the S3 managed "loading dock" storage entity and make sure it exists.
    StorageEntity storageEntity = storageDaoHelper.getStorageEntity(StorageEntity.MANAGED_LOADING_DOCK_STORAGE);

    String s3BucketName = storageHelper.getStorageBucketName(storageEntity);

    // Get the storage unit entity for this business object data in the S3 managed "loading dock" storage and make sure it exists.
    StorageUnitEntity storageUnitEntity = storageUnitDaoHelper.getStorageUnitEntity(StorageEntity.MANAGED_LOADING_DOCK_STORAGE, businessObjectDataEntity);

    // Validate that the storage unit contains exactly one storage file.
    assertHasOneStorageFile(storageUnitEntity);

    // Get the storage file entity.
    StorageFileEntity storageFileEntity = IterableUtils.get(storageUnitEntity.getStorageFiles(), 0);

    // Get the storage file path.
    String storageFilePath = storageFileEntity.getPath();

    String awsRoleArn = getStorageUploadRoleArn(storageEntity);

    Integer awsRoleDurationSeconds = getStorageUploadSessionDuration(storageEntity);

    String awsKmsKeyId = storageHelper.getStorageKmsKeyId(storageEntity);

    // Get the temporary security credentials to access S3_MANAGED_STORAGE.
    Credentials assumedSessionCredentials = stsDao
        .getTemporarySecurityCredentials(awsHelper.getAwsParamsDto(), String.valueOf(businessObjectDataEntity.getId()), awsRoleArn, awsRoleDurationSeconds,
            createUploaderPolicy(s3BucketName, storageFilePath, awsKmsKeyId));

    // Create the response.
    UploadSingleCredentialExtensionResponse response = new UploadSingleCredentialExtensionResponse();
    response.setAwsAccessKey(assumedSessionCredentials.getAccessKeyId());
    response.setAwsSecretKey(assumedSessionCredentials.getSecretAccessKey());
    response.setAwsSessionToken(assumedSessionCredentials.getSessionToken());
    response.setAwsSessionExpirationTime(HerdDateUtils.getXMLGregorianCalendarValue(assumedSessionCredentials.getExpiration()));

    return response;
}
 
Example #27
Source File: AssumedRole.java    From pipeline-aws-plugin with Apache License 2.0 4 votes vote down vote up
private AssumedRole(final Credentials credentials, final AssumedRoleUser assumedRoleUser) {
	this.credentials = credentials;
	this.assumedRoleUser = assumedRoleUser;
}
 
Example #28
Source File: AssumedRole.java    From pipeline-aws-plugin with Apache License 2.0 4 votes vote down vote up
public Credentials getCredentials() {
	return this.credentials;
}
 
Example #29
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 #30
Source File: UploadDownloadServiceImpl.java    From herd with Apache License 2.0 4 votes vote down vote up
@NamespacePermission(fields = "#namespace", permissions = NamespacePermissionEnum.READ)
@Override
public DownloadSingleInitiationResponse initiateDownloadSingle(String namespace, String businessObjectDefinitionName, String businessObjectFormatUsage,
    String businessObjectFormatFileType, Integer businessObjectFormatVersion, String partitionValue, Integer businessObjectDataVersion)
{
    // Create the business object data key.
    BusinessObjectDataKey businessObjectDataKey =
        new BusinessObjectDataKey(namespace, businessObjectDefinitionName, businessObjectFormatUsage, businessObjectFormatFileType,
            businessObjectFormatVersion, partitionValue, null, businessObjectDataVersion);

    // Validate the parameters
    businessObjectDataHelper.validateBusinessObjectDataKey(businessObjectDataKey, true, true);

    // Retrieve the persisted business object data
    BusinessObjectDataEntity businessObjectDataEntity = businessObjectDataDaoHelper.getBusinessObjectDataEntity(businessObjectDataKey);

    // Make sure the status of the business object data is VALID
    businessObjectDataHelper.assertBusinessObjectDataStatusEquals(BusinessObjectDataStatusEntity.VALID, businessObjectDataEntity);

    // Get the external storage registered against this data
    // Validate that the storage unit exists
    StorageUnitEntity storageUnitEntity = IterableUtils.get(businessObjectDataEntity.getStorageUnits(), 0);

    // Validate that the storage unit contains only 1 file
    assertHasOneStorageFile(storageUnitEntity);

    String s3BucketName = storageHelper.getStorageBucketName(storageUnitEntity.getStorage());
    String s3ObjectKey = IterableUtils.get(storageUnitEntity.getStorageFiles(), 0).getPath();

    // Get the temporary credentials
    Credentials downloaderCredentials =
        getExternalDownloaderCredentials(storageUnitEntity.getStorage(), String.valueOf(businessObjectDataEntity.getId()), s3ObjectKey);

    // Generate a pre-signed URL
    Date expiration = downloaderCredentials.getExpiration();
    S3FileTransferRequestParamsDto s3BucketAccessParams = storageHelper.getS3BucketAccessParams(storageUnitEntity.getStorage());
    String presignedUrl = s3Dao.generateGetObjectPresignedUrl(s3BucketName, s3ObjectKey, expiration, s3BucketAccessParams);

    // Construct and return the response
    DownloadSingleInitiationResponse response = new DownloadSingleInitiationResponse();
    response.setBusinessObjectData(businessObjectDataHelper.createBusinessObjectDataFromEntity(businessObjectDataEntity));
    response.setAwsAccessKey(downloaderCredentials.getAccessKeyId());
    response.setAwsSecretKey(downloaderCredentials.getSecretAccessKey());
    response.setAwsSessionToken(downloaderCredentials.getSessionToken());
    response.setAwsSessionExpirationTime(HerdDateUtils.getXMLGregorianCalendarValue(expiration));
    response.setPreSignedUrl(presignedUrl);
    return response;
}