/** * Do any initialization required by this client. In this case, * initialization consists of getting the value of the AWS region * and credentials parameters. * * @param context * the context to run with. This provides access to * initialization parameters. */ @Override public void setupTest(JavaSamplerContext context) { apigatewayBaseUrl = context.getParameter("APIGATEWAY_BASE_URL"); accessKeyId = context.getParameter("ACCESS_KEY_ID"); secretKey = context.getParameter("SECRET_KEY"); sessionToken = context.getParameter("SESSION_TOKEN"); AWSCredentials awsCredentials = new BasicSessionCredentials(accessKeyId, secretKey, sessionToken); AWSStaticCredentialsProvider awsStaticCredentialsProvider = new AWSStaticCredentialsProvider( awsCredentials); String region = context.getParameter("REGION"); client = Squash.builder().iamRegion(region) .iamCredentials((AWSCredentialsProvider) awsStaticCredentialsProvider).build(); samplerName = context.getParameter(TestElement.NAME); bookingName = context.getParameter("BOOKING_NAME"); court = context.getParameter("COURT"); courtSpan = context.getParameter("COURTSPAN"); slot = context.getParameter("SLOT"); slotSpan = context.getParameter("SLOTSPAN"); date = context.getParameter("DATE"); putOrDelete = context.getParameter("PUT_OR_DELETE"); }
@Override public Credentials get() { if (getIdentity() == null || getIdentity().trim().isEmpty() || getCredential() == null || getCredential().trim().isEmpty()) { DefaultAWSCredentialsProviderChain chain = new DefaultAWSCredentialsProviderChain(); AWSCredentials cred = chain.getCredentials(); if (cred instanceof BasicSessionCredentials) { BasicSessionCredentials sesCred = (BasicSessionCredentials)cred; return new SessionCredentials.Builder() .identity(sesCred.getAWSAccessKeyId()) .credential(sesCred.getAWSSecretKey()) .sessionToken(sesCred.getSessionToken()) .build(); } else { return new Credentials.Builder<>() .identity(cred.getAWSAccessKeyId()) .credential(cred.getAWSSecretKey()) .build(); } } return super.get(); }
public Optional<BasicSessionCredentials> load() { if (!file.exists()) { return Optional.empty(); } try { SessionCacheSchema cache = objectMapper.readValue(file, SessionCacheSchema.class); if (ZonedDateTime.now().plusSeconds(EXPIRATION_THRESHOLD_IN_SECONDS).isBefore(cache.credentials.getExpiration())) { return Optional.of(new BasicSessionCredentials(cache.credentials.accessKeyId, cache.credentials.secretAccessKey, cache.credentials.sessionToken)); } else { return Optional.empty(); } } catch (IOException e) { throw new RuntimeException(String.format("Failed to load session cache from '%s'", file.getAbsolutePath()), e); } }
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(); } }
@Override public AWSCredentials getCredentials() { AWSCredentialsProvider credentialsProvider = AWSClientFactory.getBasicCredentialsOrDefaultChain(accessKey, secretKey); AWSCredentials initialCredentials = credentialsProvider.getCredentials(); if (iamRoleArn.isEmpty()) { return initialCredentials; } else { AssumeRoleRequest assumeRequest = new AssumeRoleRequest() .withRoleArn(iamRoleArn) .withExternalId(externalId) .withDurationSeconds(3600) .withRoleSessionName("CodeBuild-Jenkins-Plugin"); AssumeRoleResult assumeResult = new AWSSecurityTokenServiceClient(initialCredentials).assumeRole(assumeRequest); return new BasicSessionCredentials( assumeResult.getCredentials().getAccessKeyId(), assumeResult.getCredentials().getSecretAccessKey(), assumeResult.getCredentials().getSessionToken()); } }
AWSSecurityTokenServiceClient getInstanceClient(AWSAttestationData info) { String access = info.getAccess(); if (access == null || access.isEmpty()) { LOGGER.error("getInstanceClient: No access key id available in instance document"); return null; } String secret = info.getSecret(); if (secret == null || secret.isEmpty()) { LOGGER.error("getInstanceClient: No secret access key available in instance document"); return null; } String token = info.getToken(); if (token == null || token.isEmpty()) { LOGGER.error("getInstanceClient: No token available in instance document"); return null; } BasicSessionCredentials creds = new BasicSessionCredentials(access, secret, token); return new AWSSecurityTokenServiceClient(creds); }
/** * Creates a client for accessing Amazon EC2 service. * * @param awsParamsDto the AWS related parameters DTO that includes optional AWS credentials and proxy information * * @return the Amazon EC2 client */ @Cacheable(DaoSpringModuleConfig.HERD_CACHE_NAME) public AmazonEC2Client getEc2Client(AwsParamsDto awsParamsDto) { // Get client configuration. ClientConfiguration clientConfiguration = awsHelper.getClientConfiguration(awsParamsDto); // If specified, use the AWS credentials passed in. if (StringUtils.isNotBlank(awsParamsDto.getAwsAccessKeyId())) { return new AmazonEC2Client( new BasicSessionCredentials(awsParamsDto.getAwsAccessKeyId(), awsParamsDto.getAwsSecretKey(), awsParamsDto.getSessionToken()), clientConfiguration); } // Otherwise, use the default AWS credentials provider chain. else { return new AmazonEC2Client(clientConfiguration); } }
/** * Creates a client for accessing Amazon EMR service. * * @param awsParamsDto the AWS related parameters DTO that includes optional AWS credentials and proxy information * * @return the Amazon EMR client */ @Cacheable(DaoSpringModuleConfig.HERD_CACHE_NAME) public AmazonElasticMapReduceClient getEmrClient(AwsParamsDto awsParamsDto) { // Get client configuration. ClientConfiguration clientConfiguration = awsHelper.getClientConfiguration(awsParamsDto); // If specified, use the AWS credentials passed in. if (StringUtils.isNotBlank(awsParamsDto.getAwsAccessKeyId())) { return new AmazonElasticMapReduceClient( new BasicSessionCredentials(awsParamsDto.getAwsAccessKeyId(), awsParamsDto.getAwsSecretKey(), awsParamsDto.getSessionToken()), clientConfiguration); } // Otherwise, use the default AWS credentials provider chain. else { return new AmazonElasticMapReduceClient(clientConfiguration); } }
@Test public void sessionToken() { S3ClientProvider provider = new S3ClientProvider(); S3Configuration s3Configuration = new S3Configuration("fakeProvidedKeyId", "fakeProvidedSecretKey", false, "fakeProvidedSessionToken", null, 5, "s3-transfer-manager-worker-", 100); ReflectionTestUtils.setField(provider, "s3Configuration", s3Configuration); BasicSessionCredentials credentials = (BasicSessionCredentials) provider.getAwsCredentials(); assertEquals("fakeProvidedKeyId", credentials.getAWSAccessKeyId()); assertEquals("fakeProvidedSecretKey", credentials.getAWSSecretKey()); assertEquals("fakeProvidedSessionToken", credentials.getSessionToken()); }
private AmazonEC2Client getClientForAccount(final String accountId, final Region region) { final AWSSecurityTokenServiceClient stsClient = new AWSSecurityTokenServiceClient(new ProfileCredentialsProvider()); final AssumeRoleRequest assumeRequest = new AssumeRoleRequest().withRoleArn( "arn:aws:iam::ACCOUNT_ID:role/fullstop-role") .withDurationSeconds(3600).withRoleSessionName( "fullstop-role"); final AssumeRoleResult assumeResult = stsClient.assumeRole(assumeRequest); final BasicSessionCredentials temporaryCredentials = new BasicSessionCredentials( assumeResult.getCredentials() .getAccessKeyId(), assumeResult.getCredentials().getSecretAccessKey(), assumeResult.getCredentials().getSessionToken()); final AmazonEC2Client amazonEC2Client = new AmazonEC2Client(temporaryCredentials); amazonEC2Client.setRegion(region); return amazonEC2Client; }
public AWSCredentials getCredentials() { AWSCredentials initialCredentials = new BasicAWSCredentials(accessKey, secretKey.getPlainText()); if (StringUtils.isBlank(iamRoleArn)) { return initialCredentials; } else { // Handle the case of delegation to instance profile if (StringUtils.isBlank(accessKey) && StringUtils.isBlank(secretKey.getPlainText()) ) { initialCredentials = (new InstanceProfileCredentialsProvider()).getCredentials(); } AssumeRoleRequest assumeRequest = createAssumeRoleRequest(iamRoleArn); AssumeRoleResult assumeResult = new AWSSecurityTokenServiceClient(initialCredentials).assumeRole(assumeRequest); return new BasicSessionCredentials( assumeResult.getCredentials().getAccessKeyId(), assumeResult.getCredentials().getSecretAccessKey(), assumeResult.getCredentials().getSessionToken()); } }
public synchronized void provideCredentials(@NonNull String bucket, @NonNull String bucketPath, @NonNull String awsKey, @NonNull String awsSecret, @NonNull String awsSessionToken) { if (hasCredentials()) { Timber.w("Credentials already provided"); return; } Timber.d("Credentials provided"); this.bucket = bucket; this.bucketPath = bucketPath; this.credentials = new BasicSessionCredentials(awsKey, awsSecret, awsSessionToken); this.s3 = new AmazonS3Client(credentials); this.transferUtility = new TransferUtility(s3, context); executeQueuedUploads(); }
@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)); }
private void onGotStreamResponse(HlsStream stream) { mStream = stream; if (mConfig.shouldAttachLocation()) { Kickflip.addLocationToStream(mContext, mStream, mEventBus); } mStream.setTitle(mConfig.getTitle()); mStream.setDescription(mConfig.getDescription()); mStream.setExtraInfo(mConfig.getExtraInfo()); mStream.setIsPrivate(mConfig.isPrivate()); if (VERBOSE) Log.i(TAG, "Got hls start stream " + stream); mS3Manager = new S3BroadcastManager(this, new BasicSessionCredentials(mStream.getAwsKey(), mStream.getAwsSecret(), mStream.getToken())); mS3Manager.setRegion(mStream.getRegion()); mS3Manager.addRequestInterceptor(mS3RequestInterceptor); mReadyToBroadcast = true; submitQueuedUploadsToS3(); mEventBus.post(new BroadcastIsBufferingEvent()); if (mBroadcastListener != null) { mBroadcastListener.onBroadcastStart(); } }
private void create() { AssumeRoleResult result = sts.assumeRole( new AssumeRoleRequest().withRoleArn( assumedRoleArn ).withExternalId( AgentConfig.ROLE_EXTERNAL_ID ).withRoleSessionName( "rs-" + RandomStringUtils.randomAlphabetic( 8 ) ) ); synchronized ( this ) { expirationDate = result.getCredentials().getExpiration().getTime(); creds = new BasicSessionCredentials( result.getCredentials().getAccessKeyId(), result.getCredentials().getSecretAccessKey(), result.getCredentials().getSessionToken() ); } }
/** * Get the basic session credentials for the template's configured IAM authentication keys * * @return a {@link BasicSessionCredentials} instance with a valid authenticated session token */ private BasicSessionCredentials getBasicSessionCredentials() { // Create a new session token if the session is expired or not initialized if (sessionCredentials == null || sessionCredentials.getExpiration().before(new Date())) sessionCredentials = getSessionCredentials(); // Create basic session credentials using the generated session token return new BasicSessionCredentials(sessionCredentials.getAccessKeyId(), sessionCredentials.getSecretAccessKey(), sessionCredentials.getSessionToken()); }
public SessionCacheSchema(final String arn, final String assumedRoleId, final BasicSessionCredentials credentials, final ZonedDateTime expiration) { this.assumedUserRole = new AssumedUserRole(arn, assumedRoleId); this.credentials = new Credentials(credentials, expiration); }
public Credentials(final BasicSessionCredentials credentials, final ZonedDateTime expiration) { this.accessKeyId = credentials.getAWSAccessKeyId(); this.secretAccessKey = credentials.getAWSSecretKey(); this.sessionToken = credentials.getSessionToken(); this.expiration = expiration.format(DateTimeFormatter.ISO_INSTANT); }
public void save(final AssumedRoleUser assumedRoleUser, final BasicSessionCredentials credentials, final ZonedDateTime expiration) { resolveCacheDirectory().mkdirs(); SessionCacheSchema cache = new SessionCacheSchema(assumedRoleUser.getArn(), assumedRoleUser.getAssumedRoleId(), credentials, expiration); try { objectMapper.writeValue(file, cache); } catch (IOException e) { throw new RuntimeException(String.format("Failed to save session cache to '%s'", file.getAbsolutePath()), e); } }
private AWSCredentials fromStaticCredentials() { //IBM bx Credentials loaded if (!StringUtils.isNullOrEmpty(profile.getIBMApiKey())){ return new BasicIBMOAuthCredentials(profile.getIBMApiKey(), profile.getIBMServiceInstanceId()); } if (StringUtils.isNullOrEmpty(profile.getAwsAccessIdKey())) { throw new SdkClientException(String.format( "Unable to load credentials into profile [%s]: AWS Access Key ID is not specified.", profile.getProfileName())); } if (StringUtils.isNullOrEmpty(profile.getAwsSecretAccessKey())) { throw new SdkClientException(String.format( "Unable to load credentials into profile [%s]: AWS Secret Access Key is not specified.", profile.getAwsSecretAccessKey())); } if (profile.getAwsSessionToken() == null) { return new BasicAWSCredentials(profile.getAwsAccessIdKey(), profile.getAwsSecretAccessKey()); } else { if (profile.getAwsSessionToken().isEmpty()) { throw new SdkClientException(String.format( "Unable to load credentials into profile [%s]: AWS Session Token is empty.", profile.getProfileName())); } return new BasicSessionCredentials(profile.getAwsAccessIdKey(), profile.getAwsSecretAccessKey(), profile.getAwsSessionToken()); } }
@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(); }
/** * Gets an Amazon S3 client from basic session credentials * * @return an authenticated Amazon S3 client */ public AmazonS3 getAmazonS3Client() { BasicSessionCredentials basicSessionCredentials = getBasicSessionCredentials(); // Create a new S3 client using the basic session credentials of the service instance return new AmazonS3Client(basicSessionCredentials); }
@Override public AWSCredentials getCredentials() { CredPair credPair = _credProvider.getCredPair(); String secret = credPair.getSecret(); if ( null != secret && secret.contains("\u001E") ) { String[] secretPair = secret.split("\u001E", 2); return new BasicSessionCredentials(credPair.getKeyId(), secretPair[0], secretPair[1]); } else { return new BasicAWSCredentials(credPair.getKeyId(), secret); } }
@Override public CredPair getCredPair() { AWSCredentials awsCreds = _credProvider.getCredentials(); String keyId = awsCreds.getAWSAccessKeyId(); String secret = awsCreds.getAWSSecretKey(); if ( awsCreds instanceof BasicSessionCredentials ) { secret = secret + "\u001E" + ((BasicSessionCredentials)awsCreds).getSessionToken(); } return new CredPair() .withKeyId(keyId) .withSecret(secret); }
@Test public void testSession() { CredPair credPair2 = new CredPair() .withKeyId("two") .withSecret("secret2\u001ESESSION"); CredProvider credProvider2 = () -> credPair2; AWSCredentialsProvider credProvider = _awsCredentialsProviderFactory.create(credProvider2); AWSCredentials creds = credProvider.getCredentials(); assertThat(creds, instanceOf(BasicSessionCredentials.class)); assertEquals("two", creds.getAWSAccessKeyId()); assertEquals("secret2", creds.getAWSSecretKey()); assertEquals("SESSION", ((BasicSessionCredentials)creds).getSessionToken()); }
@Test public void testGetS3Client() { System.setProperty(ZTSConsts.ZTS_PROP_AWS_PUBLIC_CERT, "src/test/resources/aws_public.crt"); CloudStore store = new CloudStore(null); store.credentials = new BasicSessionCredentials("accessKey", "secretKey", "token"); store.awsEnabled = true; assertNotNull(store.getS3Client()); store.awsRegion = "us-west-2"; assertNotNull(store.getS3Client()); store.close(); }
@Test public void testGetTokenServiceClient() { CloudStore store = new CloudStore(null); store.credentials = new BasicSessionCredentials("accessKey", "secretKey", "token"); store.awsEnabled = true; assertNotNull(store.getTokenServiceClient()); store.close(); }
private AWSCredentials buildCredentials(final String accessKeyId, final String secretAccessKey, final String sessionToken) { if (isNullOrEmpty(sessionToken)) { return new BasicAWSCredentials(accessKeyId, secretAccessKey); } else { return new BasicSessionCredentials(accessKeyId, secretAccessKey, sessionToken); } }
@Override public AWSCredentials getCredentials() { AwsCredential herdAwsCredential = herdAWSCredentialsProvider.getAwsCredential(); return new BasicSessionCredentials(herdAwsCredential.getAwsAccessKey(), herdAwsCredential.getAwsSecretKey(), herdAwsCredential.getAwsSessionToken()); }
@Override public synchronized void refresh() { final GetJobDetailsRequest getJobDetailsRequest = new GetJobDetailsRequest().withJobId(jobId); final GetJobDetailsResult getJobDetailsResult = codePipelineClient.getJobDetails(getJobDetailsRequest); final com.amazonaws.services.codepipeline.model.AWSSessionCredentials credentials = getJobDetailsResult.getJobDetails().getData().getArtifactCredentials(); this.lastRefreshedInstant = Instant.now(); this.credentials = new BasicSessionCredentials( credentials.getAccessKeyId(), credentials.getSecretAccessKey(), credentials.getSessionToken()); }
private AWSSessionCredentials createSessionCredentials(Config config, SecretProvider secrets, BasicAWSCredentials baseCredential) { List<AcceptableUri> acceptableUris = buildAcceptableUriForSessionCredentials(config, baseCredential); if (!config.get("temp_credentials", Boolean.class, true)) { return new BasicSessionCredentials( baseCredential.getAWSAccessKeyId(), baseCredential.getAWSSecretKey(), null ); } AWSSessionCredentialsFactory sessionCredentialsFactory = new AWSSessionCredentialsFactory(baseCredential, acceptableUris); Optional<String> roleArn = getSecretOptionalValue(secrets, "role_arn"); if (roleArn.isPresent()) { sessionCredentialsFactory.withRoleArn(roleArn.get()); Optional<String> roleSessionName = secrets.getSecretOptional("role_session_name"); if (roleSessionName.isPresent()) { sessionCredentialsFactory.withRoleSessionName(roleSessionName.get()); } } Optional<Integer> durationSeconds = config.getOptional("session_duration", Integer.class); if (durationSeconds.isPresent()) { sessionCredentialsFactory.withDurationSeconds(durationSeconds.get()); } return sessionCredentialsFactory.get(); }
public AWSCredentials getCredentials(String mfaToken) { AWSCredentials initialCredentials = new BasicAWSCredentials(accessKey, secretKey.getPlainText()); AssumeRoleRequest assumeRequest = createAssumeRoleRequest(iamRoleArn) .withSerialNumber(iamMfaSerialNumber) .withTokenCode(mfaToken); AssumeRoleResult assumeResult = new AWSSecurityTokenServiceClient(initialCredentials).assumeRole(assumeRequest); return new BasicSessionCredentials( assumeResult.getCredentials().getAccessKeyId(), assumeResult.getCredentials().getSecretAccessKey(), assumeResult.getCredentials().getSessionToken()); }
@Test public final void addsSessionTokenHeaderWhenSessionCredentialsAreProvided() { String sessionToken = "sessionToken"; StaticCredentialsProvider credentialsProvider = new StaticCredentialsProvider(new BasicSessionCredentials("accessKey", "secretKey", sessionToken)); testObject = new V4RequestSigner(credentialsProvider, REGION_NAME, SERVICE_NAME, currentDate); HttpPost request = createTestRequest(); testObject.signRequest(request); Header[] tokenHeaders = request.getHeaders(SESSION_TOKEN_HEADER); assertEquals(1, tokenHeaders.length); assertEquals(SESSION_TOKEN_HEADER, tokenHeaders[0].getName()); assertEquals(sessionToken, tokenHeaders[0].getValue()); }
@VisibleForTesting protected S3Client newS3Client() throws Exception { AccountCredentials account = getAccountCredentials(); BasicSessionCredentials basicSessionCredentials = new BasicSessionCredentials(account.getStorage_access_key(), account.getStorage_secret_key(), account.getSession_token()); final AmazonS3Client client = new AmazonS3Client(basicSessionCredentials); return new S3Client() { @Override public void shutdown() { client.shutdown(); } @Override public ObjectListing listObjects(ListObjectsRequest listObjectsRequest) { return client.listObjects(listObjectsRequest); } @Override public S3Object getObject(String bucket, String key) { return client.getObject(bucket, key); } }; }
@RequestMapping(value="/config", method = RequestMethod.GET) public String config(ModelMap model) { config.refreshConfigurationProvider(); model.addAttribute("templateName", "config"); model.addAttribute("configLoadedFrom", config.getConfigurationProvider().getPrettyName()); model.addAttribute("appConfig", config.toString()); model.addAttribute("accessKey", config.getAWSCredentialsProvider().getCredentials().getAWSAccessKeyId()); model.addAttribute("isToken", config.getAWSCredentialsProvider().getCredentials() instanceof BasicSessionCredentials); // Inject info about S3 config if(config.getConfigurationProvider() instanceof S3ConfigurationProvider) { model.addAttribute("isS3Config", true); model.addAttribute("configBucket", ((S3ConfigurationProvider)config.getConfigurationProvider()).getBucket()); model.addAttribute("configKey", ((S3ConfigurationProvider)config.getConfigurationProvider()).getKey()); } // Handle ProvisionableResources Map<String, ProvisionableResource> provisionableResources = context.getBeansOfType(ProvisionableResource.class); // Let the view know if there are any unprovisioned resources Boolean allProvisioned = true; for (Map.Entry<String, ProvisionableResource> entry : provisionableResources.entrySet()) { if(entry.getValue().getState() != ProvisionableResource.ProvisionState.PROVISIONED) { allProvisioned = false; break; } } // Set provisionables model.addAttribute("allProvisioned", allProvisioned); model.addAttribute("prs", provisionableResources); // Set EditableConfigurationProperties editableConfigurationProperties.initialize(); model.addAttribute("ecp", editableConfigurationProperties); return "base"; }
/** * The UploadPolicy method creates the S3 upload policy for the aMediaManager application. * Much of this is hard coded and would have to change with any changes to the fields in the S3 * upload form. * * @param key this is not currently used. * @param redirectUrl this is the URL to which S3 will redirect the browser on successful upload. * @return the upload policy string is returned. */ String generateUploadPolicy(String s3BucketName, String keyPrefix, AWSCredentialsProvider credsProvider, String redirectUrl) { Calendar dateTime = Calendar.getInstance(); // add the offset from UTC dateTime.add(Calendar.MILLISECOND, -dateTime.getTimeZone().getOffset(dateTime.getTimeInMillis())); // add 15 minutes more for skew dateTime.add(Calendar.MINUTE, 15); SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); String expirationDate = dateFormatter.format(dateTime.getTime()); StringBuilder sb = new StringBuilder(); sb.append("{ \"expiration\": \"" + expirationDate + "\","); sb.append("\"conditions\": [ { \"bucket\": \"" + s3BucketName + "\" }, "); sb.append("[\"starts-with\", \"$key\", \"" + keyPrefix + "/\"], "); sb.append("{ \"success_action_redirect\": \"" + redirectUrl + "\" },"); sb.append("[\"eq\", \"$x-amz-meta-bucket\", \"" + s3BucketName + "\"], "); sb.append("[\"starts-with\", \"$x-amz-meta-owner\", \"\"], "); sb.append("[\"starts-with\", \"$x-amz-meta-uuid\", \"\"], "); sb.append("[\"starts-with\", \"$x-amz-meta-title\", \"\"], "); sb.append("[\"starts-with\", \"$x-amz-meta-tags\", \"\"], "); sb.append("[\"starts-with\", \"$x-amz-meta-createdDate\", \"\"], "); sb.append("[\"starts-with\", \"$x-amz-meta-description\", \"\"], "); sb.append("[\"starts-with\", \"$x-amz-meta-privacy\", \"\"], "); sb.append("[\"starts-with\", \"$Content-Type\", \"video/\"], "); if(credsProvider.getCredentials() instanceof BasicSessionCredentials) { sb.append("[\"starts-with\", \"$x-amz-security-token\", \"\"], "); } sb.append("[\"content-length-range\", 0, 1073741824] ] }"); return sb.toString(); }
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; }
/** * Gets the AWS Access Key, AWS Secret Key and Security Token currently stored in Shared Preferences. Then creates a Credentials object * and returns that object. */ public static AWSCredentials getCredentialsFromSharedPreferences( SharedPreferences sharedPreferences ) { String accessKey = AmazonSharedPreferencesWrapper.getValueFromSharedPreferences( sharedPreferences, AWS_ACCESS_KEY ); String secretKey = AmazonSharedPreferencesWrapper.getValueFromSharedPreferences( sharedPreferences, AWS_SECRET_KEY ); String securityToken = AmazonSharedPreferencesWrapper.getValueFromSharedPreferences( sharedPreferences, AWS_SECURITY_TOKEN ); return new BasicSessionCredentials( accessKey, secretKey, securityToken ); }
public BasicSessionCredentials retrieveSessionCredentials(AwsCredentialView awsCredential) { LOGGER.debug("retrieving session credential"); AWSSecurityTokenServiceClient client = awsSecurityTokenServiceClient(); AssumeRoleRequest assumeRoleRequest = new AssumeRoleRequest() .withDurationSeconds(DEFAULT_SESSION_CREDENTIALS_DURATION) .withExternalId(externalId) .withRoleArn(awsCredential.getRoleArn()) .withRoleSessionName("hadoop-provisioning"); AssumeRoleResult result = client.assumeRole(assumeRoleRequest); return new BasicSessionCredentials( result.getCredentials().getAccessKeyId(), result.getCredentials().getSecretAccessKey(), result.getCredentials().getSessionToken()); }