Java 类com.amazonaws.services.securitytoken.model.Credentials 实例源码

项目:herd    文件:MockStsOperationsImpl.java   
@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;
}
项目:service-block-samples    文件:LambdaCredentialsProvider.java   
/**
 * 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;
}
项目:alexa-meets-polly    文件:ConvertService.java   
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();
    }
}
项目:athenz    文件:CloudStoreTest.java   
@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.setAssumeAWSRole(true);

    AWSTemporaryCredentials awsCreds = cloudStore.assumeAWSRole("account", "syncer", "athenz.syncer");
    assertNotNull(awsCreds);
    assertEquals(awsCreds.getAccessKeyId(), "accesskeyid");
    assertEquals(awsCreds.getSessionToken(), "sessiontoken");
    assertEquals(awsCreds.getSecretAccessKey(), "secretaccesskey");
}
项目:herd    文件:StorageHelper.java   
/**
 * 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;
}
项目:proyecti-aws-cognito    文件:LoginServiceImpl.java   
@Override
public WifResponseDTO loginWithAssumeRoleWithWebIdentity(String token, IdentityProviderEnum identityProvider) 
{
    /*
     *  The token returned by GetOpenIdToken can be passed to the STS operation 
     *  AssumeRoleWithWebIdentity to retrieve AWS credentials.
     *
     *  The ProviderId parameter for an STS call with a Cognito OpenID token is 
     *  cognito-identity.amazonaws.com.
     */ 
    final AssumeRoleWithWebIdentityRequest request = new AssumeRoleWithWebIdentityRequest()
        .withWebIdentityToken(token)
        .withProviderId(identityProvider.getValueAsString())
        .withRoleArn(ROLE_ARN)
        .withRoleSessionName("wifSession")
        .withDurationSeconds(300);

    final AssumeRoleWithWebIdentityResult result = awsSecurityTokenServiceClient.assumeRoleWithWebIdentity(request);
    final Credentials stsCredentials = result.getCredentials();
    final BasicSessionCredentials credentials = new BasicSessionCredentials(stsCredentials.getAccessKeyId(),
                                                                      stsCredentials.getSecretAccessKey(),
                                                                      stsCredentials.getSessionToken());

    return new WifResponseDTO(result.getSubjectFromWebIdentityToken(), new AmazonS3Client(credentials));
}
项目:reinvent2013-mobile-photo-share    文件:IdentityTokenVendingMachine.java   
/**
 * 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());
}
项目:tdl-auth    文件:AuthLambdaHandlerTest.java   
private static FederatedUserCredentials validCredentials() {
    return new FederatedUserCredentials(
            "expectedRegion",
            "expectedBucket",
            "expectedUser",
            new Credentials("expectedKeyId",
                    "expectedSecretKey",
                    "expectedSessionToken",
                    null));
}
项目:tdl-auth    文件:FederatedUserCredentialsProviderTest.java   
@Before
public void setUp() throws Exception {
    Credentials federatedUserCredentials = federatedUserCredentialsProvider
            .getFederatedTokenFor(TEST_USERNAME)
            .getCredentials();
    federatedS3Client = AmazonS3ClientBuilder.standard()
            .withCredentials(new AWSStaticCredentialsProvider(new BasicSessionCredentials(
                    federatedUserCredentials.getAccessKeyId(),
                    federatedUserCredentials.getSecretAccessKey(),
                    federatedUserCredentials.getSessionToken())))
            .withRegion(TEST_AWS_REGION)
            .build();
}
项目:spring-boot-starter-amazon-s3    文件:AmazonS3Template.java   
/**
 * 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;
}
项目:athenz    文件:CloudStore.java   
public AWSTemporaryCredentials assumeAWSRole(String account, String roleName, String principal) {

        if (!awsEnabled) {
            throw new ResourceException(ResourceException.INTERNAL_SERVER_ERROR,
                    "AWS Support not enabled");
        }

        AssumeRoleRequest req = getAssumeRoleRequest(account, roleName, principal);

        AWSTemporaryCredentials tempCreds = null;
        try {
            AWSSecurityTokenServiceClient client = getTokenServiceClient();
            AssumeRoleResult res = client.assumeRole(req);

            Credentials awsCreds = res.getCredentials();
            tempCreds = new AWSTemporaryCredentials()
                .setAccessKeyId(awsCreds.getAccessKeyId())
                .setSecretAccessKey(awsCreds.getSecretAccessKey())
                .setSessionToken(awsCreds.getSessionToken())
                .setExpiration(Timestamp.fromMillis(awsCreds.getExpiration().getTime()));

        } catch (Exception ex) {
            LOGGER.error("CloudStore: assumeAWSRole - unable to assume role: " + ex.getMessage());
            return null;
        }

        return tempCreds;
    }
项目:herd    文件:EmrHelper.java   
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());
}
项目:herd    文件:StsDaoImpl.java   
/**
 * 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();
}
项目:aws-codedeploy-plugin    文件:AWSClients.java   
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;
}
项目:reinvent2013-mobile-photo-share    文件:AnonymousTokenVendingMachine.java   
/**
 * 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());
}
项目:reinvent2013-mobile-photo-share    文件:TemporaryCredentialManagement.java   
/**
 * 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);
    }
}
项目:reinvent2013-mobile-photo-share    文件:TemporaryCredentialManagement.java   
/**
 * 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);
    }
}
项目:reinvent2013-mobile-photo-share    文件:Utilities.java   
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);
    }
项目:strongbox    文件:ProfileCredentialProvider.java   
/**
 * 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;
    }
}
项目:tdl-auth    文件:FederatedUserCredentials.java   
public FederatedUserCredentials(String region, String bucket, String username, Credentials credentials) {
    this.region = region;
    this.bucket = bucket;
    this.username = username;
    this.credentials = credentials;
}
项目:tdl-auth    文件:FederatedUserCredentials.java   
Credentials getCredentials() {
    return credentials;
}
项目:herd    文件:UploadDownloadServiceImpl.java   
@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;
}
项目:herd    文件:UploadDownloadServiceImpl.java   
@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;
}
项目:herd    文件:UploadDownloadServiceImpl.java   
private Credentials getDownloaderCredentialsNoKmsKey(StorageEntity storageEntity, String sessionName, String s3ObjectKey)
{
    return stsDao.getTemporarySecurityCredentials(awsHelper.getAwsParamsDto(), sessionName, getStorageDownloadRoleArn(storageEntity),
        getStorageDownloadSessionDuration(storageEntity), createDownloaderPolicy(storageHelper.getStorageBucketName(storageEntity), s3ObjectKey));
}
项目:herd    文件:UploadDownloadServiceImpl.java   
@Override
public DownloadBusinessObjectDefinitionSampleDataFileSingleInitiationResponse initiateDownloadSingleSampleFile(
    DownloadBusinessObjectDefinitionSampleDataFileSingleInitiationRequest request)
{
    // Validate and trim the request parameters.
    validateDownloadBusinessObjectDefinitionSampleDataFileSingleInitiationRequest(request);

    // Get the business object definition sample data file key.
    BusinessObjectDefinitionSampleDataFileKey businessObjectDefinitionSampleDataFileKey = request.getBusinessObjectDefinitionSampleDataFileKey();

    // Get the business object definition key.
    BusinessObjectDefinitionKey businessObjectDefinitionKey = new BusinessObjectDefinitionKey(businessObjectDefinitionSampleDataFileKey.getNamespace(),
        businessObjectDefinitionSampleDataFileKey.getBusinessObjectDefinitionName());

    // Get the business object definition entity and ensure it exists.
    BusinessObjectDefinitionEntity businessObjectDefinitionEntity =
        businessObjectDefinitionDaoHelper.getBusinessObjectDefinitionEntity(businessObjectDefinitionKey);

    // Get the sample data file exists for the business object definition and ensure it exists.
    BusinessObjectDefinitionSampleDataFileEntity businessObjectDefinitionSampleDataFileEntity =
        getBusinessObjectDefinitionSampleDataFileEntity(businessObjectDefinitionEntity, businessObjectDefinitionSampleDataFileKey);

    // Retrieve the storage related information.
    StorageEntity storageEntity = businessObjectDefinitionSampleDataFileEntity.getStorage();
    String s3BucketName = storageHelper.getStorageBucketName(storageEntity);
    String s3ObjectKey = businessObjectDefinitionSampleDataFileKey.getDirectoryPath() + businessObjectDefinitionSampleDataFileKey.getFileName();

    String sessionID = UUID.randomUUID().toString();
    // Get the temporary credentials.
    Credentials downloaderCredentials = getDownloaderCredentialsNoKmsKey(storageEntity, sessionID, s3ObjectKey);

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

    // Create the download business object definition sample data file single initiation response.
    DownloadBusinessObjectDefinitionSampleDataFileSingleInitiationResponse response =
        new DownloadBusinessObjectDefinitionSampleDataFileSingleInitiationResponse();
    response.setBusinessObjectDefinitionSampleDataFileKey(
        new BusinessObjectDefinitionSampleDataFileKey(businessObjectDefinitionEntity.getNamespace().getCode(), businessObjectDefinitionEntity.getName(),
            businessObjectDefinitionSampleDataFileEntity.getDirectoryPath(), businessObjectDefinitionSampleDataFileEntity.getFileName()));
    response.setAwsS3BucketName(s3BucketName);
    response.setAwsAccessKey(downloaderCredentials.getAccessKeyId());
    response.setAwsSecretKey(downloaderCredentials.getSecretAccessKey());
    response.setAwsSessionToken(downloaderCredentials.getSessionToken());
    response.setAwsSessionExpirationTime(HerdDateUtils.getXMLGregorianCalendarValue(expiration));
    response.setPreSignedUrl(presignedUrl);

    // Return the response.
    return response;
}
项目:herd    文件:UploadDownloadServiceImpl.java   
@NamespacePermission(fields = "#request.businessObjectDefinitionKey.namespace", permissions = {NamespacePermissionEnum.WRITE_DESCRIPTIVE_CONTENT,
    NamespacePermissionEnum.WRITE})
@Override
public UploadBusinessObjectDefinitionSampleDataFileInitiationResponse initiateUploadSampleFile(
    UploadBusinessObjectDefinitionSampleDataFileInitiationRequest request)
{
    validateUploadBusinessObjectDefinitionSampleDataFileInitiationRequest(request);

    BusinessObjectDefinitionKey businessObjectDefinitionKey = request.getBusinessObjectDefinitionKey();
    // Get the business object definition entity and ensure it exists.
    BusinessObjectDefinitionEntity businessObjectDefinitionEntity =
        businessObjectDefinitionDaoHelper.getBusinessObjectDefinitionEntity(businessObjectDefinitionKey);
    businessObjectDefinitionKey.setNamespace(businessObjectDefinitionEntity.getNamespace().getCode());
    businessObjectDefinitionKey.setBusinessObjectDefinitionName(businessObjectDefinitionEntity.getName());

    UploadBusinessObjectDefinitionSampleDataFileInitiationResponse response = new UploadBusinessObjectDefinitionSampleDataFileInitiationResponse();
    StorageEntity storageEntity = storageDaoHelper.getStorageEntity(StorageEntity.SAMPLE_DATA_FILE_STORAGE);

    String s3BucketName = storageHelper.getStorageBucketName(storageEntity);
    String s3EndPoint = storageHelper.getS3BucketAccessParams(storageEntity).getS3Endpoint();
    String awsRoleArn = getStorageUploadRoleArn(storageEntity);
    String sessionID = UUID.randomUUID().toString();
    String s3KeyPrefix = s3KeyPrefixHelper.buildS3KeyPrefix(storageEntity, businessObjectDefinitionKey);
    s3KeyPrefix = StringUtils.appendIfMissing(s3KeyPrefix, "/");
    //need to add star for aws authorization
    String s3Path = s3KeyPrefix + "*";

    Integer awsRoleDurationSeconds = getStorageUploadSessionDuration(storageEntity);

    Credentials assumedSessionCredentials = stsDao
        .getTemporarySecurityCredentials(awsHelper.getAwsParamsDto(), sessionID, awsRoleArn, awsRoleDurationSeconds,
            createUploaderPolicyNoKmsKey(s3BucketName, s3Path));

    response.setAwsAccessKey(assumedSessionCredentials.getAccessKeyId());
    response.setAwsSecretKey(assumedSessionCredentials.getSecretAccessKey());
    response.setAwsSessionToken(assumedSessionCredentials.getSessionToken());
    response.setAwsSessionExpirationTime(HerdDateUtils.getXMLGregorianCalendarValue(assumedSessionCredentials.getExpiration()));

    response.setAwsS3BucketName(s3BucketName);
    response.setBusinessObjectDefinitionKey(businessObjectDefinitionKey);
    response.setS3Endpoint(s3EndPoint);
    response.setS3KeyPrefix(s3KeyPrefix);
    return response;
}
项目:herd    文件:StorageUnitServiceImpl.java   
/**
 * Creates and returns a set of AWS credentials which can be used to access the S3 object indicated by the given business object data and storage.
 *
 * @param businessObjectDataKey Business object data key
 * @param createNewVersion true to create credentials for the next version up from the latest business object data, otherwise, uses specified data version
 * in data key.
 * @param storageName Name of storage to access
 * @param isUpload true if this credential is to upload, false to download
 *
 * @return Credentials which has the permissions to perform the specified actions at the specified storage.
 */
private AwsCredential getBusinessObjectDataS3Credential(BusinessObjectDataKey businessObjectDataKey, Boolean createNewVersion, String storageName,
    boolean isUpload)
{
    Assert.isTrue(StringUtils.isNotBlank(storageName), "storageName must be specified");
    Assert.isTrue(businessObjectDataKey.getBusinessObjectDataVersion() != null || createNewVersion != null,
        "One of businessObjectDataVersion or createNewVersion must be specified.");
    Assert.isTrue(businessObjectDataKey.getBusinessObjectDataVersion() == null || !Boolean.TRUE.equals(createNewVersion),
        "createNewVersion must be false or unspecified when businessObjectDataVersion is specified.");

    /*
     * Choose configurations based on whether this is an upload or download operation.
     */
    ConfigurationValue roleArnConfigurationValue;
    ConfigurationValue defaultSessionDurationConfigurationValue;
    ConfigurationValue sessionDurationConfigurationValue;
    S3Actions[] s3Actions;
    KmsActions[] kmsActions;

    if (isUpload)
    {
        roleArnConfigurationValue = ConfigurationValue.S3_ATTRIBUTE_NAME_UPLOAD_ROLE_ARN;
        defaultSessionDurationConfigurationValue = ConfigurationValue.AWS_S3_DEFAULT_UPLOAD_SESSION_DURATION_SECS;
        sessionDurationConfigurationValue = ConfigurationValue.S3_ATTRIBUTE_NAME_UPLOAD_SESSION_DURATION_SECS;
        s3Actions = new S3Actions[] {S3Actions.PutObject, S3Actions.DeleteObject};
        kmsActions = new KmsActions[] {KmsActions.GENERATE_DATA_KEY, KmsActions.DECRYPT};
    }
    else
    {
        roleArnConfigurationValue = ConfigurationValue.S3_ATTRIBUTE_NAME_DOWNLOAD_ROLE_ARN;
        defaultSessionDurationConfigurationValue = ConfigurationValue.AWS_S3_DEFAULT_DOWNLOAD_SESSION_DURATION_SECS;
        sessionDurationConfigurationValue = ConfigurationValue.S3_ATTRIBUTE_NAME_DOWNLOAD_SESSION_DURATION_SECS;
        s3Actions = new S3Actions[] {S3Actions.GetObject};
        kmsActions = new KmsActions[] {KmsActions.DECRYPT};
    }

    StorageEntity storageEntity = storageDaoHelper.getStorageEntity(storageName.trim());
    String roleArn = storageHelper.getStorageAttributeValueByName(configurationHelper.getProperty(roleArnConfigurationValue), storageEntity, true);
    Integer durationSeconds = storageHelper
        .getStorageAttributeIntegerValueByName(configurationHelper.getProperty(sessionDurationConfigurationValue), storageEntity,
            configurationHelper.getProperty(defaultSessionDurationConfigurationValue, Integer.class));
    String bucketName = storageHelper
        .getStorageAttributeValueByName(configurationHelper.getProperty(ConfigurationValue.S3_ATTRIBUTE_NAME_BUCKET_NAME), storageEntity, true);

    S3KeyPrefixInformation s3KeyPrefixInformation = getS3KeyPrefixImpl(businessObjectDataKey, null, storageName, createNewVersion);
    /*
     * Policy is different based on whether this is meant for downloading or uploading.
     * However, both uploader and downloader requires a ListBucket at the bucket level.
     */
    AwsPolicyBuilder awsPolicyBuilder =
        new AwsPolicyBuilder().withS3Prefix(bucketName, s3KeyPrefixInformation.getS3KeyPrefix(), s3Actions).withS3(bucketName, null, S3Actions.ListObjects);

    /*
     * Only add KMS policies if the storage specifies a KMS ID
     */
    String kmsKeyId = getStorageKmsKeyId(storageEntity);
    if (kmsKeyId != null)
    {
        awsPolicyBuilder.withKms(kmsKeyId.trim(), kmsActions);
    }

    Credentials credentials = stsDao
        .getTemporarySecurityCredentials(awsHelper.getAwsParamsDto(), UUID.randomUUID().toString(), roleArn, durationSeconds, awsPolicyBuilder.build());

    AwsCredential awsCredential = new AwsCredential();
    awsCredential.setAwsAccessKey(credentials.getAccessKeyId());
    awsCredential.setAwsSecretKey(credentials.getSecretAccessKey());
    awsCredential.setAwsSessionToken(credentials.getSessionToken());
    awsCredential.setAwsSessionExpirationTime(HerdDateUtils.getXMLGregorianCalendarValue(credentials.getExpiration()));
    return awsCredential;
}
项目:herd    文件:StsDao.java   
public Credentials getTemporarySecurityCredentials(AwsParamsDto awsParamsDto, String sessionName, String awsRoleArn, int awsRoleDurationSeconds, 
Policy policy);
项目:herd    文件:StsDaoTest.java   
@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);
}
项目:herd    文件:StsDaoTest.java   
@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);
}
项目:herd    文件:UploadDownloadServiceImpl.java   
/**
 * Gets a temporary session token that is only good for downloading the specified object key from the given bucket for a limited amount of time.
 *
 * @param storageEntity The storage entity of the external storage
 * @param sessionName the session name to use for the temporary credentials.
 * @param s3ObjectKey the S3 object key of the path to the data in the bucket.
 *
 * @return {@link Credentials} temporary session token
 */
private Credentials getExternalDownloaderCredentials(StorageEntity storageEntity, String sessionName, String s3ObjectKey)
{
    return stsDao.getTemporarySecurityCredentials(awsHelper.getAwsParamsDto(), sessionName, getStorageDownloadRoleArn(storageEntity),
        getStorageDownloadSessionDuration(storageEntity),
        createDownloaderPolicy(storageHelper.getStorageBucketName(storageEntity), s3ObjectKey, storageHelper.getStorageKmsKeyId(storageEntity)));
}