@Override public void run(Webhook webhook, String login, String email, String name, String subject, String content) { SNSWebhookApp webhookApp = (SNSWebhookApp) webhook.getWebhookApp(); String topicArn = webhookApp.getTopicArn(); String awsAccount = webhookApp.getAwsAccount(); String awsSecret = webhookApp.getAwsSecret(); String region = webhookApp.getRegion(); AmazonSNSClient snsClient = new AmazonSNSClient(new BasicAWSCredentials(awsAccount, awsSecret)); snsClient.setRegion(Region.getRegion(Regions.fromName(region))); try { PublishRequest publishReq = new PublishRequest() .withTopicArn(topicArn) .withMessage(getMessage(login, email, name, subject, content)); snsClient.publish(publishReq); } catch (Exception e) { LOGGER.log(Level.SEVERE, "Cannot send notification to SNS service", e); } finally { LOGGER.log(Level.INFO, "Webhook runner terminated"); } }
public AwsIot(Node root, String region, String accessKeyId, String secretAccessKey, KeyStore keyStore, String keyPassword) { AWSCredentials awsCredentials = new BasicAWSCredentials(accessKeyId, secretAccessKey); this.client = new AWSIotClient(awsCredentials); this.client.withRegion(Regions.fromName(region)); String endpoint = getEndpoint(); String clientId = UUID.randomUUID().toString(); if (keyStore != null && keyPassword != null) { this.mqttClient = new AWSIotMqttClient(endpoint, clientId, keyStore, keyPassword); } else { this.mqttClient = new AWSIotMqttClient(endpoint, clientId, accessKeyId, secretAccessKey); } try { this.mqttClient.connect(); } catch (AWSIotException e) { throw new RuntimeException("Failed to connect to AWS IoT service", e); } this.root = root; }
public void deploy(AwsKeyPair keyPair, String region, final String restApiName, final String stage, Proxy proxy) { final AWSCredentialsProvider credentials = new AWSStaticCredentialsProvider( new BasicAWSCredentials(keyPair.key, keyPair.secret)); ClientConfiguration cc = Util.createConfiguration(proxy); AmazonApiGateway ag = AmazonApiGatewayClientBuilder.standard().withCredentials(credentials) // .withClientConfiguration(cc) // .withRegion(region) // .build(); GetRestApisResult apis = ag.getRestApis(new GetRestApisRequest().withLimit(10000)); Optional<RestApi> api = apis.getItems().stream().filter(item -> item.getName().equals(restApiName)).findFirst(); RestApi a = api.orElseThrow(() -> new RuntimeException("no rest api found with name='" + restApiName + "'")); String restApiId = a.getId(); log.info("creating deployment of " + restApiId + " to stage " + stage); CreateDeploymentResult r = ag .createDeployment(new CreateDeploymentRequest().withRestApiId(restApiId).withStageName(stage)); Map<String, Map<String, MethodSnapshot>> summary = r.getApiSummary(); log.info("created deployment"); log.info("summary=" + summary); }
public static AWSCredentialsProvider buildCredentials(Logger logger, DeprecationLogger deprecationLogger, Settings settings, Settings repositorySettings, String clientName) { try (SecureString key = getConfigValue(repositorySettings, settings, clientName, S3Repository.ACCESS_KEY_SETTING, S3Repository.Repository.KEY_SETTING, S3Repository.Repositories.KEY_SETTING); SecureString secret = getConfigValue(repositorySettings, settings, clientName, S3Repository.SECRET_KEY_SETTING, S3Repository.Repository.SECRET_SETTING, S3Repository.Repositories.SECRET_SETTING)) { if (key.length() == 0 && secret.length() == 0) { logger.debug("Using instance profile credentials"); return new PrivilegedInstanceProfileCredentialsProvider(); } else { logger.debug("Using basic key/secret credentials"); return new StaticCredentialsProvider(new BasicAWSCredentials(key.toString(), secret.toString())); } } }
@Override public Seq<Binding<?>> bindings(Environment environment, Configuration configuration) { GlobalParams.AWS_ACCESS_KEY = Scala.orNull(configuration.getString("AWS_ACCESS_KEY", scala.Option.empty())); GlobalParams.AWS_SECRET_KEY = Scala.orNull(configuration.getString("AWS_SECRET_KEY", scala.Option.empty())); GlobalParams.AWS_S3_BUCKET = Scala.orNull(configuration.getString("AWS_S3_BUCKET", scala.Option.empty())); String accessKey = GlobalParams.AWS_ACCESS_KEY; String secretKey = GlobalParams.AWS_SECRET_KEY; s3Bucket = GlobalParams.AWS_S3_BUCKET; if ((accessKey != null) && (secretKey != null)) { awsCredentials = new BasicAWSCredentials(accessKey, secretKey); amazonS3 = new AmazonS3Client(awsCredentials); Logger.info("Using S3 Bucket: " + s3Bucket); } return seq( bind(S3Plugin.class).to(S3PluginImpl.class) ); }
/** * Inits the. */ public void init() { if (this.awsAccessKey == null) { this.awsAccessKey = System.getenv("AWS_ACCESS_KEY"); if (this.awsAccessKey == null) { this.awsAccessKey = System.getProperty("com.oneops.aws.accesskey"); } } if (this.awsSecretKey == null) { this.awsSecretKey = System.getenv("AWS_SECRET_KEY"); if (this.awsSecretKey == null) { this.awsSecretKey = System.getProperty("com.oneops.aws.secretkey"); } } emailClient = new AmazonSimpleEmailServiceClient( new BasicAWSCredentials(awsAccessKey, awsSecretKey)); }
@Override protected void obtainResource() throws Exception { // See https://github.com/mhart/kinesalite#cbor-protocol-issues-with-the-java-sdk System.setProperty(SDKGlobalConfiguration.AWS_CBOR_DISABLE_SYSTEM_PROPERTY, "true"); this.resource = AmazonKinesisAsyncClientBuilder.standard() .withClientConfiguration( new ClientConfiguration() .withMaxErrorRetry(0) .withConnectionTimeout(1000)) .withEndpointConfiguration( new AwsClientBuilder.EndpointConfiguration("http://localhost:" + this.port, Regions.DEFAULT_REGION.getName())) .withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials("", ""))) .build(); // Check connection this.resource.listStreams(); }
@Override public AmazonEC2Async amazonEC2Async() { User user = authenticationService.getCurrentUser(); String accessKey = user.getAwsKey(); String secretKey = user.getAwsSecret(); String region = user.getAwsRegion(); if (secretKey.equals("") || accessKey.equals("") || region.equals("")) { return null; } BasicAWSCredentials basicAWSCredentials = new BasicAWSCredentials( accessKey, secretKey); return AmazonEC2AsyncClientBuilder.standard().withRegion(region) .withCredentials(new AWSStaticCredentialsProvider(basicAWSCredentials)) .build(); }
@Override public AmazonEC2Async amazonEC2Async(User user) { String accessKey = user.getAwsKey(); String secretKey = user.getAwsSecret(); String region = user.getAwsRegion(); if (secretKey.equals("") || accessKey.equals("") || region.equals("")) { return null; } BasicAWSCredentials basicAWSCredentials = new BasicAWSCredentials( accessKey, secretKey); return AmazonEC2AsyncClientBuilder.standard().withRegion(region) .withCredentials(new AWSStaticCredentialsProvider(basicAWSCredentials)) .build(); }
/** * 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; }
/** * Tests two profiles having same name. The second profile overrides the first profile. Also * checks if the AWS Access Key ID and AWS Secret Access Key are mapped properly under the * profile. */ @Test public void testTwoProfileWithSameName() throws URISyntaxException { ProfilesConfigFile profile = new ProfilesConfigFile( ProfileResourceLoader.profilesWithSameProfileName().asFile()); AWSCredentials defaultCred = profile.getCredentials(DEFAULT_PROFILE_NAME); assertNotNull(defaultCred); assertTrue(defaultCred instanceof BasicAWSCredentials); AWSCredentials testCred = profile.getCredentials(PROFILE_NAME_TEST); assertNotNull(testCred); assertTrue(testCred instanceof AWSSessionCredentials); AWSSessionCredentials testSessionCred = (AWSSessionCredentials) testCred; assertEquals(testSessionCred.getAWSAccessKeyId(), "testProfile2"); assertEquals(testSessionCred.getAWSSecretKey(), "testProfile2"); assertEquals(testSessionCred.getSessionToken(), "testProfile2"); }
@Test public void request_credentials_takes_precendence_over_client_credentials() { final String awsAccessKeyId = "foo"; final String awsSecretAccessKey = "bar"; final AWSCredentials reqCredentials = new BasicAWSCredentials(awsAccessKeyId, awsSecretAccessKey); EmptyAmazonWebServiceRequest req = new EmptyAmazonWebServiceRequest(); req.setRequestCredentials(reqCredentials); AWSCredentialsProvider actual = CredentialUtils.getCredentialsProvider(req, null); Assert.assertThat(actual, Matchers.instanceOf(StaticCredentialsProvider .class)); assertEquals(awsAccessKeyId, actual.getCredentials().getAWSAccessKeyId()); assertEquals(awsSecretAccessKey, actual.getCredentials().getAWSSecretKey()); }
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException{ try{ String customerID = request.getParameter("customerID"); BasicAWSCredentials awsCredentials = new BasicAWSCredentials("test", "test"); AmazonSimpleDBClient sdbc = new AmazonSimpleDBClient(awsCredentials); String query = "select * from invoices where customerID = '" + customerID; SelectResult sdbResult = sdbc.select(new SelectRequest(query)); //BAD SelectResult sdbResult2 = sdbc.select(new SelectRequest(query, false)); //BAD SelectRequest sdbRequest = new SelectRequest(); SelectResult sdbResult3 = sdbc.select(sdbRequest.withSelectExpression(query)); //BAD String query2 = "select * from invoices where customerID = 123"; SelectResult sdbResult4 = sdbc.select(new SelectRequest(query2)); //OK }catch(Exception e){ System.out.println(e); } }
@Override public AmazonS3Client load(S3ClientKey clientKey) throws Exception { logger.debug("Opening S3 client connection for {}", clientKey); ClientConfiguration clientConf = new ClientConfiguration(); clientConf.setProtocol(clientKey.isSecure ? Protocol.HTTPS : Protocol.HTTP); // Proxy settings (if configured) clientConf.setProxyHost(clientKey.s3Config.get(Constants.PROXY_HOST)); if (clientKey.s3Config.get(Constants.PROXY_PORT) != null) { clientConf.setProxyPort(Integer.valueOf(clientKey.s3Config.get(Constants.PROXY_PORT))); } clientConf.setProxyDomain(clientKey.s3Config.get(Constants.PROXY_DOMAIN)); clientConf.setProxyUsername(clientKey.s3Config.get(Constants.PROXY_USERNAME)); clientConf.setProxyPassword(clientKey.s3Config.get(Constants.PROXY_PASSWORD)); clientConf.setProxyWorkstation(clientKey.s3Config.get(Constants.PROXY_WORKSTATION)); if (clientKey.accessKey == null){ return new AmazonS3Client(new AnonymousAWSCredentialsProvider(), clientConf); } else { return new AmazonS3Client(new BasicAWSCredentials(clientKey.accessKey, clientKey.secretKey), clientConf); } }
@Before public void setUp() throws Exception { context = mock(Context.class); when(context.getLogger()).thenReturn(System.out::println); handler = new AuthLambdaHandler(TEST_AWS_REGION, TEST_JWT_KEY_ARN, TEST_VIDEO_STORAGE_BUCKET, TEST_USER_ACCESS_KEY_ID, TEST_USER_SECRET_ACCESS_KEY); AWSKMS kmsClient = AWSKMSClientBuilder.standard() .withRegion(TEST_AWS_REGION) .withCredentials(new AWSStaticCredentialsProvider( new BasicAWSCredentials(TEST_USER_ACCESS_KEY_ID, TEST_USER_SECRET_ACCESS_KEY)) ) .build(); kmsEncrypt = new KMSEncrypt(kmsClient, TEST_JWT_KEY_ARN); }
/** * S3 储存客户端 * * @return 客户端 */ @Bean @ConditionalOnProperty(value = "bigbug.storage.s3.enable", havingValue = "true") AmazonS3Client amazonS3Client() { ClientConfiguration clientConfig = new ClientConfiguration(); clientConfig.setProtocol(Protocol.HTTP); BasicAWSCredentials basicAWSCredentials = new BasicAWSCredentials( storageProperties.getStorage().getS3().getAccessKey(), storageProperties.getStorage().getS3().getSecretKey()); return (AmazonS3Client) AmazonS3ClientBuilder.standard() .withClientConfiguration(clientConfig) .withEndpointConfiguration( new AwsClientBuilder.EndpointConfiguration( storageProperties.getStorage().getS3().getEndpoint(), Regions.DEFAULT_REGION.getName())) .withCredentials(new AWSStaticCredentialsProvider(basicAWSCredentials)) .build(); }
/** * Creates a new S3 configuration cache. * @param bucket The S3 bucket. * @param prefix The S3 object prefix. * @param pathPattern The path pattern. * @param accessKey The (optional) S3 access key. * @param secretKey The (optional) S3 secret key. * @param region The AWS region (e.g. us-east-1). * @throws IOException Thrown if the configuration cannot be read. */ public S3ConfigurationCache(String bucket, String prefix, String pathPattern, String accessKey, String secretKey, String region) throws IOException { this.bucket = bucket; this.prefix = prefix; this.pathPattern = pathPattern; if (!StringUtils.isEmpty(accessKey)) { s3 = AmazonS3Client.builder() .withCredentials(new AWSStaticCredentialsProvider( new BasicAWSCredentials(accessKey, secretKey))) .withRegion(Regions.fromName(region)) .build(); } else { s3 = AmazonS3Client.builder() .withRegion(Regions.fromName(region)) .build(); } }
public S3StorageService() { CloudStorageSettings settings = Settings.instance().getCloudStorage(); if (settings == null) { throw new ConfigException("You are missing the section [cloudStorage]\naccessToken=...\nsecret=... in your stallion.toml"); } if (empty(settings.getAccessToken())) { throw new ConfigException("You are missing the setting accessKey in the stallion.toml section [cloudStorage]"); } if (empty(settings.getSecret())) { throw new ConfigException("You are missing the setting secret in the stallion.toml section [cloudStorage]"); } accessToken = settings.getAccessToken(); secret = settings.getSecret(); AWSCredentials credentials = new BasicAWSCredentials(accessToken, secret); client = new AmazonS3Client(credentials); }
public com.amazonaws.services.kinesis.AmazonKinesis build(AmazonKinesis kinesisProperties) { com.amazonaws.services.kinesis.AmazonKinesisClientBuilder clientBuilder = com.amazonaws.services.kinesis.AmazonKinesisClientBuilder.standard(); clientBuilder.setRegion(kinesisProperties.getRegion()); clientBuilder.setCredentials(new AWSCredentialsProvider() { @Override public AWSCredentials getCredentials() { return new BasicAWSCredentials(kinesisProperties.getKey(), kinesisProperties.getSecret()); } @Override public void refresh() { } }); clientBuilder.setClientConfiguration(new ClientConfiguration()); return clientBuilder.build(); }
public static AmazonS3Client getS3Client(AuthCredentialsServiceState credentials, String regionId) { ClientConfiguration configuration = new ClientConfiguration(); configuration.withRetryPolicy(new RetryPolicy(new CustomRetryCondition(), DEFAULT_BACKOFF_STRATEGY, DEFAULT_MAX_ERROR_RETRY, false)); AWSStaticCredentialsProvider awsStaticCredentialsProvider = new AWSStaticCredentialsProvider( new BasicAWSCredentials(credentials.privateKeyId, EncryptionUtils.decrypt(credentials.privateKey))); AmazonS3ClientBuilder amazonS3ClientBuilder = AmazonS3ClientBuilder .standard() .withClientConfiguration(configuration) .withCredentials(awsStaticCredentialsProvider) .withRegion(regionId); if (isAwsClientMock()) { throw new IllegalArgumentException("AWS Mock does not support S3 client"); } return (AmazonS3Client) amazonS3ClientBuilder.build(); }
public static AmazonEC2 getEC2SynchronousClient(AuthCredentialsServiceState credentials, String region) { ClientConfiguration configuration = new ClientConfiguration(); configuration.withRetryPolicy(new RetryPolicy(new CustomRetryCondition(), DEFAULT_BACKOFF_STRATEGY, DEFAULT_MAX_ERROR_RETRY, true)); AWSStaticCredentialsProvider awsStaticCredentialsProvider = new AWSStaticCredentialsProvider( new BasicAWSCredentials(credentials.privateKeyId, EncryptionUtils.decrypt(credentials.privateKey))); AmazonEC2ClientBuilder ec2ClientBuilder = AmazonEC2ClientBuilder.standard() .withCredentials(awsStaticCredentialsProvider) .withRegion(region) .withClientConfiguration(configuration); return ec2ClientBuilder.build(); }
@Before public void setup() { store = new InMemoryStorage(); metrics = new InMemoryCollectorMetrics(); collector = new SQSCollector.Builder() .queueUrl(sqsRule.queueUrl()) .parallelism(2) .waitTimeSeconds(1) // using short wait time to make test teardown faster .endpointConfiguration(new EndpointConfiguration(sqsRule.queueUrl(), "us-east-1")) .credentialsProvider(new AWSStaticCredentialsProvider(new BasicAWSCredentials("x", "x"))) .metrics(metrics) .sampler(CollectorSampler.ALWAYS_SAMPLE) .storage(store) .build() .start(); }
@Override protected void tearDown() throws Exception { final File theFile = new File(TEST_FILE_NAME); theFile.delete(); if (s3Account != null) { final AmazonS3Client s3 = new AmazonS3Client( new BasicAWSCredentials(s3Account.keyId, s3Account.secretKey)); String hash = s3Account.getHashedName(); if (s3.doesBucketExist(hash)) { for (S3ObjectSummary summary : s3.listObjects(hash).getObjectSummaries()) { s3.deleteObject(s3Account.getHashedName(), summary.getKey()); } } } super.tearDown(); }
private AmazonS3Client getAmazonS3Client(BackupRestoreContext ctx) throws URISyntaxException { final String accessKey = ctx.getAccountId(); final String secretKey = ctx.getSecretKey(); String endpoint = getEndpoint(ctx); LOGGER.info("endpoint: {}", endpoint); final BasicAWSCredentials basicAWSCredentials = new BasicAWSCredentials(accessKey, secretKey); final AmazonS3Client amazonS3Client = new AmazonS3Client(basicAWSCredentials); amazonS3Client.setEndpoint(endpoint); if (ctx.usesEmc()) { final S3ClientOptions options = new S3ClientOptions(); options.setPathStyleAccess(true); amazonS3Client.setS3ClientOptions(options); } return amazonS3Client; }
private void connectToS3(String accessKey, String secretKey, String endpoint, boolean secure, boolean pathStyle) { LOG.info("'{}','{}','{}'", accessKey, secretKey, endpoint); AWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey); ClientConfiguration clientConfiguration = new ClientConfiguration() .withProtocol(secure ? Protocol.HTTPS : Protocol.HTTP) .withUserAgentPrefix("s3browser") .withSignerOverride("S3SignerType"); s3Client = new AmazonS3Client(credentials, clientConfiguration); s3Client.setS3ClientOptions(S3ClientOptions.builder() .setPathStyleAccess(pathStyle) .disableChunkedEncoding() .build()); s3Client.setEndpoint(endpoint); }
@Test public void testBasic() { CredPair credPair1 = new CredPair() .withKeyId("one") .withSecret("secret1"); AtomicInteger refreshCount1 = new AtomicInteger(); CredProvider credProvider1 = new CredProvider() { public CredPair getCredPair() { return credPair1; } public void refresh() { refreshCount1.incrementAndGet(); } }; AWSCredentialsProvider credProvider = _awsCredentialsProviderFactory.create(credProvider1); AWSCredentials creds = credProvider.getCredentials(); assertThat(creds, instanceOf(BasicAWSCredentials.class)); assertEquals("one", creds.getAWSAccessKeyId()); assertEquals("secret1", creds.getAWSSecretKey()); assertEquals(0, refreshCount1.get()); credProvider.refresh(); assertEquals(1, refreshCount1.get()); }
/** * Creates an {@link S3Connector} instance with embedded {@link AmazonS3 Amazon Web Services S3 SDK Client} from * {@link S3ServiceInfo}. * @param serviceInfo S3ServiceInfo provided by {@link org.springframework.cloud.cloudfoundry.CloudFoundryServiceInfoCreator} * implementation included within the application. * @param serviceConnectorConfig * @return */ @Override public S3Connector create(S3ServiceInfo serviceInfo, ServiceConnectorConfig serviceConnectorConfig) { AWSCredentials credentials = new BasicAWSCredentials(serviceInfo.getAccessKey(), serviceInfo.getSecretKey()); AWSCredentialsProvider credentialsProvider = new AWSStaticCredentialsProvider(credentials); AwsClientBuilder.EndpointConfiguration endpointConfig = new AwsClientBuilder.EndpointConfiguration( serviceInfo.getEndpoint(), Region.getRegion(Regions.DEFAULT_REGION).getName()); AmazonS3 amazonS3 = AmazonS3ClientBuilder .standard() .withEndpointConfiguration(endpointConfig) .withCredentials(credentialsProvider) .enablePathStyleAccess() .build(); if (serviceInfo.getBucket() != null) { log.debug("Creating connector addressing ECS bucket: " + serviceInfo.getBucket()); return new S3Connector(amazonS3, serviceInfo.getEndpoint(), serviceInfo.getBucket()); } else { log.debug("Creating connector addressing ECS namespace."); return new S3Connector(amazonS3, serviceInfo.getEndpoint()); } }
@Test public void testProvide() { Env env = new Env().register("DYNAMODB_ENDPOINT", "fakeendpoint"); ClientConfiguration config = new ClientConfiguration(); config.setRetryPolicy(PredefinedRetryPolicies.NO_RETRY_POLICY); AWSCredentialsProvider credentialsProvider = new StaticCredentialsProvider( new BasicAWSCredentials("fake_access_key_id", "fake_secret_access_key")); AmazonDynamoDBFactory factory = new AmazonDynamoDBFactory(env, credentialsProvider, config); AmazonDynamoDB dynamoDB = factory.provide(); String message = ""; try { dynamoDB.listTables(); } catch (AmazonClientException e) { message = e.getMessage(); } assertTrue(message.startsWith("Unable to execute HTTP request: fakeendpoint")); factory.dispose(dynamoDB); }
void deploy(AwsKeyPair keyPair, String region, String zipFilename, String functionName, Proxy proxy) { long t = System.currentTimeMillis(); final AWSCredentialsProvider credentials = new AWSStaticCredentialsProvider( new BasicAWSCredentials(keyPair.key, keyPair.secret)); AWSLambda lambda = AWSLambdaClientBuilder.standard().withCredentials(credentials) .withClientConfiguration(Util.createConfiguration(proxy)).withRegion(region).build(); byte[] bytes; try { bytes = IOUtils.toByteArray(new FileInputStream(zipFilename)); } catch (IOException e) { throw new RuntimeException(e); } DecimalFormat df = new DecimalFormat("0.000"); log.info("deploying " + zipFilename + ", length=" + df.format(bytes.length / 1024.0 / 1024.0) + "MB, to functionName=" + functionName); lambda.updateFunctionCode( // new UpdateFunctionCodeRequest() // .withFunctionName(functionName) // .withPublish(true) // .withZipFile(ByteBuffer.wrap(bytes))); log.info("deployed in " + (System.currentTimeMillis() - t) + "ms"); }
@Override public void execute() throws MojoExecutionException, MojoFailureException { Proxy proxy = new Proxy(httpsProxyHost, httpsProxyPort, httpsProxyUsername, httpsProxyPassword); AwsKeyPair keyPair = Util.getAwsKeyPair(serverId, awsAccessKey, awsSecretAccessKey, settings, decrypter); final AWSCredentialsProvider credentials = new AWSStaticCredentialsProvider( new BasicAWSCredentials(keyPair.key, keyPair.secret)); ClientConfiguration cc = Util.createConfiguration(proxy); AmazonIdentityManagement iam = AmazonIdentityManagementClientBuilder // .standard() // .withRegion(region) // .withCredentials(credentials) // .withClientConfiguration(cc) // .build(); String accountId = iam.getUser().getUser().getUserId(); project.getProperties().setProperty("aws.account.id", accountId); getLog().info("The following properties have been set for the project"); getLog().info("aws.account.id=" + accountId); }
@VisibleForTesting String getAwsAuthorizationToken(String accessKeyId, String secretAccessKey) { try { AWSCredentials credentials = new BasicAWSCredentials(accessKeyId, secretAccessKey); AmazonECRClient amazonECRClient = new AmazonECRClient(credentials); GetAuthorizationTokenResult tokenResult = amazonECRClient.getAuthorizationToken(new GetAuthorizationTokenRequest()); List<AuthorizationData> authData = tokenResult.getAuthorizationData(); if (!authData.isEmpty()) { return authData.get(0).getAuthorizationToken(); } LOG.warn("Failed to retrieve AWS ECR token"); } catch (AmazonECRException e) { LOG.warn(e.getLocalizedMessage()); } return null; }
@Before public void setup() throws Exception { client = new AmazonS3Client(new BasicAWSCredentials(accessKey, secretKey)); client.createBucket(testMeta.bucketKey); inputDir = testMeta.baseDirectory + File.separator + "input"; File file1 = new File(inputDir + File.separator + FILE_1); File file2 = new File(inputDir + File.separator + FILE_2); FileUtils.writeStringToFile(file1, FILE_1_DATA); FileUtils.writeStringToFile(file2, FILE_2_DATA); client.putObject(new PutObjectRequest(testMeta.bucketKey, "input/" + FILE_1, file1)); client.putObject(new PutObjectRequest(testMeta.bucketKey, "input/" + FILE_2, file2)); files = SCHEME + "://" + accessKey + ":" + secretKey + "@" + testMeta.bucketKey + "/input"; }
@Override public void configure(String name, Properties props, NameSpace ns) throws LDAPException { this.name = name; this.accessKey = props.getProperty("accessKey"); this.secretKey = props.getProperty("secretKey"); this.userDomain = props.getProperty("userDomain"); this.groupDomain = props.getProperty("groupDomain"); this.userDN = new DN("ou=users," + ns.getBase().getDN().toString()); this.groupDN = new DN("ou=groups," + ns.getBase().getDN().toString()); this.baseDN = new DN(ns.getBase().getDN().toString()); this.sdb = new AmazonSimpleDBClient(new BasicAWSCredentials(accessKey,secretKey)); }
@Test public void shouldSignRequest() throws Exception { // the values used in this test are from the example http://docs.aws.amazon.com/amazonglacier/latest/dev/amazon-glacier-signing-requests.html String hash = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"; String uri = "https://glacier.us-east-1.amazonaws.com/-/vaults/examplevault"; HttpPut request = new HttpPut(uri); request.setHeader("Host", "glacier.us-east-1.amazonaws.com"); request.setHeader("x-amz-date", "20120525T002453Z"); request.setHeader("x-amz-glacier-version", "2012-06-01"); String signature = awsRequestSignerV4.createV4Signature(request, "glacier", "us-east-1", "/-/vaults/examplevault", new BasicAWSCredentials(ACCESS_KEY, SECRET_KEY), hash); String expectedSignature = "AWS4-HMAC-SHA256 Credential=AKIAIOSFODNN7EXAMPLE/20120525/us-east-1/glacier/aws4_request, " + "SignedHeaders=host;x-amz-date;x-amz-glacier-version, Signature=3ce5b2f2fffac9262b4da9256f8d086b4aaf42eba5f111c21681a65a127b7c2a"; assertThat(signature).isEqualTo(expectedSignature); }
@Test public void shouldSignRequestWithQueryParam() throws Exception { // the values used in this test are from the example http://docs.aws.amazon.com/AmazonS3/latest/API/sig-v4-header-based-auth.html String hash = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"; String uri = "https://examplebucket.s3.amazonaws.com?max-keys=2&prefix=J"; HttpGet request = new HttpGet(uri); request.setHeader("Host", "examplebucket.s3.amazonaws.com"); request.setHeader("x-amz-date", "20130524T000000Z"); request.setHeader("x-amz-content-sha256", hash); String signature = awsRequestSignerV4.createV4Signature(request, "s3", "us-east-1", "/", new BasicAWSCredentials(ACCESS_KEY, SECRET_KEY), hash); String expectedSignature = "AWS4-HMAC-SHA256 Credential=AKIAIOSFODNN7EXAMPLE/20130524/us-east-1/s3/aws4_request, " + "SignedHeaders=host;x-amz-content-sha256;x-amz-date, Signature=34b48302e7b5fa45bde8084f4b7868a86f0a534bc59db6670ed5711ef69dc6f7"; assertThat(signature).isEqualTo(expectedSignature); }
@Override public AWSCredentials getCredentials() { // if profile is specified, use that final String profile = configuration.get(AWSConstants.PROFILE); if(!StringUtils.isNullOrEmpty(profile)) { return new ProfileCredentialsProvider(profile).getCredentials(); } // then try access key and secret final String accessKeyId = configuration.get(AWSConstants.ACCESS_KEY_ID); final String secretAccessKey = configuration.get(AWSConstants.SECRET_ACCESS_KEY); if(!StringUtils.isNullOrEmpty(accessKeyId) && !StringUtils.isNullOrEmpty(secretAccessKey)) { return new BasicAWSCredentials(accessKeyId, secretAccessKey); } // fall back to default return new DefaultAWSCredentialsProviderChain().getCredentials(); }
@BeforeClass public static void setUpClass() throws IOException, InterruptedException { File dir = new File(new File("target", UUID.randomUUID().toString()), "fakes3_root").getAbsoluteFile(); Assert.assertTrue(dir.mkdirs()); fakeS3Root = dir.getAbsolutePath(); port = TestUtil.getFreePort(); fakeS3 = new FakeS3(fakeS3Root, port); Assume.assumeTrue("Please install fakes3 in your system", fakeS3.fakes3Installed()); //Start the fakes3 server executorService = Executors.newSingleThreadExecutor(); executorService.submit(fakeS3); BasicAWSCredentials credentials = new BasicAWSCredentials("foo", "bar"); s3client = AmazonS3ClientBuilder .standard() .withCredentials(new AWSStaticCredentialsProvider(credentials)) .withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration("http://localhost:" + port, null)) .withPathStyleAccessEnabled(true) .withChunkedEncodingDisabled(true) // FakeS3 does not correctly calculate checksums with chunked encoding enabled. .build(); TestUtil.createBucket(s3client, BUCKET_NAME); TestUtil.createBucket(s3client, SECOND_BUCKET_NAME); }
public static AWSClients fromBasicCredentials( final Region region, final String awsAccessKey, final String awsSecretKey, final String proxyHost, final int proxyPort, final String pluginVersion) { return new AWSClients( region, new BasicAWSCredentials(awsAccessKey, awsSecretKey), proxyHost, proxyPort, pluginVersion, new CodePipelineClientFactory(), new S3ClientFactory()); }
private static Optional<AWSCredentials> getAwsCredentials(URI uri, Configuration conf) { String accessKey = conf.get(S3_ACCESS_KEY); String secretKey = conf.get(S3_SECRET_KEY); String userInfo = uri.getUserInfo(); if (userInfo != null) { int index = userInfo.indexOf(':'); if (index < 0) { accessKey = userInfo; } else { accessKey = userInfo.substring(0, index); secretKey = userInfo.substring(index + 1); } } if (isNullOrEmpty(accessKey) || isNullOrEmpty(secretKey)) { return Optional.empty(); } return Optional.of(new BasicAWSCredentials(accessKey, secretKey)); }
@Before public void setUp() throws Exception { assumeThat(TEST_S3_ENDPOINT, not(isEmptyOrNullString())); projectDir = folder.getRoot().toPath().resolve("foobar"); config = folder.newFile().toPath(); client = DigdagClient.builder() .host(server.host()) .port(server.port()) .build(); AWSCredentials credentials = new BasicAWSCredentials(TEST_S3_ACCESS_KEY_ID, TEST_S3_SECRET_ACCESS_KEY); s3 = new AmazonS3Client(credentials); s3.setEndpoint(TEST_S3_ENDPOINT); s3.createBucket(archiveBucket); s3.createBucket(logStorageBucket); }