Skip to content

Instantly share code, notes, and snippets.

@bogovicj
Last active August 4, 2023 20:49
Show Gist options
  • Save bogovicj/953681b645b3eb4c1ba841221330ec04 to your computer and use it in GitHub Desktop.
Save bogovicj/953681b645b3eb4c1ba841221330ec04 to your computer and use it in GitHub Desktop.
Fiji S3 credentials tests
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.AnonymousAWSCredentials;
import com.amazonaws.auth.DefaultAWSCredentialsProviderChain;
import com.amazonaws.client.builder.AwsClientBuilder.EndpointConfiguration;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.ListObjectsV2Request;
endpoint = "uk1s3.embassy.ebi.ac.uk"
bucketName = "idr"
/*
* this builder fails with :
* Exception in thread "main" com.amazonaws.services.s3.model.AmazonS3Exception: null
* (Service: Amazon S3; Status Code: 403; Error Code: InvalidAccessKeyId; Request ID: tx0000000000000012662a7-0064c9238e-18ba72e3-default; S3 Extended Request ID: 18ba72e3-default-default; Proxy: null), S3 Extended Request ID: 18ba72e3-default-default
*
* because IDR does not recognized my credentials
*/
//s3 = failsForJohn(endpoint);
/*
* This works because IDR is happy
*/
s3 = worksForJohn(endpoint);
println( "does bucket exist: " + s3.doesBucketExistV2(bucketName));
println( "can list bucket : " + canListBucket(s3, bucketName));
def worksForJohn(endpoint) {
builder = AmazonS3ClientBuilder.standard();
// use anonymous credentials
builder.withCredentials( new AWSStaticCredentialsProvider( new AnonymousAWSCredentials()))
.setEndpointConfiguration( new EndpointConfiguration(endpoint, ""));
return builder.build();
}
def failsForJohn(endpoint) {
// try to get credentials using the default methos
AWSCredentials credentials;
try {
credentials = new DefaultAWSCredentialsProviderChain().getCredentials();
System.out.println( "Found credentials: " + credentials );
} catch (final Exception e) {
System.out.println("Could not load AWS credentials, falling back to anonymous.");
return null;
}
builder = AmazonS3ClientBuilder.standard();
builder.withCredentials(new DefaultAWSCredentialsProviderChain())
.setEndpointConfiguration( new EndpointConfiguration(endpoint, ""));
return builder.build();
}
def boolean canListBucket( final AmazonS3 s3, final String bucket) {
final ListObjectsV2Request request = new ListObjectsV2Request();
request.setBucketName(bucket);
request.setMaxKeys(1);
try {
// list objects will throw an AmazonS3Exception (Access Denied) if this client does not have access
s3.listObjectsV2(request);
return true;
} catch (final AmazonS3Exception e) {
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment