S3: List All Buckets with STS Credentials
See more AWS Security Token Service Examples
Uses all three temporary credential fields from the private XML file produced by either GetSessionToken or AssumeRole. Validates the response root, nonempty credential fields and ISO 8601 expiration before connecting, then checks expiry with a 60-second margin before each page. Does not print credential data, renew it automatically, or infer freshness merely from the presence of a file.
Uses Chilkat.Rest/AuthAws with Signature Version 4, service s3, explicit us-west-2 signing region, a matching regional endpoint, and TLS certificate verification. STS issuance region does not fix the service-request signing region. The session token is sent in the signed query on every request; do not log the request URL. Configure the appropriate endpoint for other partitions.
Requests max-buckets=100 and follows S3's ContinuationToken, including after an empty page. Tokens are opaque, repeated tokens stop enumeration, and a 10,000-page bound reports incomplete results. Requires s3:ListAllMyBuckets. Lists general purpose buckets owned by the authenticated account, not every bucket the caller can access. Directory buckets are excluded. Does not depend on Owner.DisplayName. Pagination is important for accounts with elevated bucket quotas, where unpaginated listing is rejected.
Pre-protect the credential file and output environment. This read-only consumer does not change the XML file. A production credential provider should coordinate refresh and publication of a complete credential set rather than partially updating it while requests are running.
Chilkat Objective-C Downloads
#import <CkoStringBuilder.h>
#import <CkoXml.h>
#import <NSString.h>
#import <CkoDateTime.h>
#import <CkoAuthAws.h>
#import <CkoRest.h>
#import <CkoSocket.h>
#import <CkoHashtable.h>
BOOL success = NO;
CkoStringBuilder *stringCompare = [[CkoStringBuilder alloc] init];
// Assumes Chilkat is unlocked. See Global Unlock Sample.
// Accept the private XML handoff from either GetSessionToken or AssumeRole.
CkoXml *xmlToken = [[CkoXml alloc] init];
xmlToken.Strict = YES;
success = [xmlToken LoadXmlFile: @"qa_data/tokens/aws_session_token.xml"];
if (success != YES) {
NSLog(@"%@",@"Could not load the private STS credential file.");
return;
}
NSString *credentialPath = @"";
[stringCompare SetString: xmlToken.Tag];
BOOL stringMatch1 = [stringCompare ContentsEqual: @"GetSessionTokenResponse" caseSensitive: YES];
if (stringMatch1 == YES) {
credentialPath = @"GetSessionTokenResult|Credentials";
}
[stringCompare SetString: xmlToken.Tag];
BOOL stringMatch2 = [stringCompare ContentsEqual: @"AssumeRoleResponse" caseSensitive: YES];
if (stringMatch2 == YES) {
credentialPath = @"AssumeRoleResult|Credentials";
}
[stringCompare SetString: credentialPath];
BOOL stringMatch3 = [stringCompare ContentsEqual: @"" caseSensitive: YES];
if (stringMatch3 == YES) {
NSLog(@"%@",@"Expected a GetSessionToken or AssumeRole credential response.");
return;
}
NSString *accessKey = 0;
NSString *secretKey = 0;
NSString *sessionToken = 0;
NSString *expiration = 0;
CkoStringBuilder *path = [[CkoStringBuilder alloc] init];
success = [path SetString: credentialPath];
if (success != YES) {
NSLog(@"%@",@"Could not build credential path.");
return;
}
success = [path Append: @"|AccessKeyId"];
if (success != YES) {
NSLog(@"%@",@"Could not build credential path.");
return;
}
accessKey = [xmlToken GetChildContent: [path GetAsString]];
[stringCompare SetString: accessKey];
BOOL stringMatch4 = [stringCompare ContentsEqual: @"" caseSensitive: YES];
if ((xmlToken.LastMethodSuccess != YES) || (stringMatch4 == YES)) {
NSLog(@"%@",@"Missing or empty AccessKeyId.");
return;
}
success = [path SetString: credentialPath];
if (success != YES) {
NSLog(@"%@",@"Could not build credential path.");
return;
}
success = [path Append: @"|SecretAccessKey"];
if (success != YES) {
NSLog(@"%@",@"Could not build credential path.");
return;
}
secretKey = [xmlToken GetChildContent: [path GetAsString]];
[stringCompare SetString: secretKey];
BOOL stringMatch5 = [stringCompare ContentsEqual: @"" caseSensitive: YES];
if ((xmlToken.LastMethodSuccess != YES) || (stringMatch5 == YES)) {
NSLog(@"%@",@"Missing or empty SecretAccessKey.");
return;
}
success = [path SetString: credentialPath];
if (success != YES) {
NSLog(@"%@",@"Could not build credential path.");
return;
}
success = [path Append: @"|SessionToken"];
if (success != YES) {
NSLog(@"%@",@"Could not build credential path.");
return;
}
sessionToken = [xmlToken GetChildContent: [path GetAsString]];
[stringCompare SetString: sessionToken];
BOOL stringMatch6 = [stringCompare ContentsEqual: @"" caseSensitive: YES];
if ((xmlToken.LastMethodSuccess != YES) || (stringMatch6 == YES)) {
NSLog(@"%@",@"Missing or empty SessionToken.");
return;
}
success = [path SetString: credentialPath];
if (success != YES) {
NSLog(@"%@",@"Could not build credential path.");
return;
}
success = [path Append: @"|Expiration"];
if (success != YES) {
NSLog(@"%@",@"Could not build credential path.");
return;
}
expiration = [xmlToken GetChildContent: [path GetAsString]];
[stringCompare SetString: expiration];
BOOL stringMatch7 = [stringCompare ContentsEqual: @"" caseSensitive: YES];
if ((xmlToken.LastMethodSuccess != YES) || (stringMatch7 == YES)) {
NSLog(@"%@",@"Missing or empty Expiration.");
return;
}
CkoDateTime *expires = [[CkoDateTime alloc] init];
CkoDateTime *now = [[CkoDateTime alloc] init];
success = [expires SetFromTimestamp: expiration];
if (success != YES) {
NSLog(@"%@",@"Stored expiration is invalid.");
return;
}
success = [now SetFromCurrentSystemTime];
if (success != YES) {
NSLog(@"%@",@"Could not read current time.");
return;
}
if ([[expires DiffSeconds: now] intValue] <= 60) {
NSLog(@"%@",@"Stored credentials are expired or expire within 60 seconds; obtain fresh credentials.");
return;
}
// This S3 region is independent of the region that issued the STS credentials.
NSString *region = @"us-west-2";
CkoStringBuilder *endpoint = [[CkoStringBuilder alloc] init];
[endpoint Append: @"s3."];
[endpoint Append: region];
[endpoint Append: @".amazonaws.com"];
CkoAuthAws *aws = [[CkoAuthAws alloc] init];
aws.AccessKey = accessKey;
aws.SecretKey = secretKey;
aws.Region = region;
aws.ServiceName = @"s3";
aws.SignatureVersion = [NSNumber numberWithInt:4];
CkoRest *rest = [[CkoRest alloc] init];
rest.ConnectTimeoutMs = [NSNumber numberWithInt:20000];
rest.IdleTimeoutMs = [NSNumber numberWithInt:60000];
rest.VerboseLogging = NO;
success = [rest SetAuthAws: aws];
if (success != YES) {
NSLog(@"%@",@"Could not configure request signing.");
return;
}
// Keep this verified Socket alive while Rest uses its connection.
CkoSocket *connection = [[CkoSocket alloc] init];
connection.RequireSslCertVerify = YES;
connection.MaxReadIdleMs = [NSNumber numberWithInt:60000];
connection.MaxSendIdleMs = [NSNumber numberWithInt:60000];
success = [connection Connect: [endpoint GetAsString] port: [NSNumber numberWithInt: 443] ssl: YES maxWaitMs: [NSNumber numberWithInt: 20000]];
if (success != YES) {
NSLog(@"%@",@"TLS connection failed; inspect diagnostics privately.");
return;
}
success = [rest UseConnection: connection autoReconnect: YES];
if (success != YES) {
NSLog(@"%@",@"Could not attach TLS connection.");
return;
}
CkoXml *xml = [[CkoXml alloc] init];
xml.Strict = YES;
NSString *value = 0;
CkoHashtable *seenTokens = [[CkoHashtable alloc] init];
NSString *continuation = @"";
NSString *responseXml = 0;
int page = 0;
int index;
BOOL more = YES;
while ((more == YES)) {
if (page == 10000) {
NSLog(@"%@",@"Page bound reached; bucket enumeration is incomplete.");
return;
}
success = [now SetFromCurrentSystemTime];
if (success != YES) {
NSLog(@"%@",@"Could not read current time.");
return;
}
if ([[expires DiffSeconds: now] intValue] <= 60) {
NSLog(@"%@",@"Credentials are expiring; obtain fresh credentials before continuing the listing.");
return;
}
page = page + 1;
success = [rest ClearAllQueryParams];
if (success != YES) {
NSLog(@"%@",@"Could not clear parameters from the previous page.");
return;
}
// All three credential components are required. Never log this signed URL.
success = [rest AddQueryParam: @"X-Amz-Security-Token" value: sessionToken];
if (success != YES) {
NSLog(@"%@",@"Could not set X-Amz-Security-Token.");
return;
}
success = [rest AddQueryParam: @"max-buckets" value: @"100"];
if (success != YES) {
NSLog(@"%@",@"Could not set max-buckets.");
return;
}
[stringCompare SetString: continuation];
BOOL stringMatch8 = [stringCompare ContentsEqual: @"" caseSensitive: YES];
if (stringMatch8 != YES) {
success = [rest AddQueryParam: @"continuation-token" value: continuation];
if (success != YES) {
NSLog(@"%@",@"Could not set continuation-token.");
return;
}
}
responseXml = [rest FullRequestNoBody: @"GET" uriPath: @"/"];
if (rest.LastMethodSuccess != YES) {
NSLog(@"%@",@"S3 request did not complete; enumeration is incomplete.");
return;
}
success = [xml LoadXml: responseXml];
if ([rest.ResponseStatusCode intValue] != 200) {
NSLog(@"%@%d",@"S3 HTTP status: ",[rest.ResponseStatusCode intValue]);
if (success == YES) {
value = [xml GetChildContent: @"Code"];
if (xml.LastMethodSuccess == YES) {
NSLog(@"%@%@",@"AWS error code: ",value);
}
value = [xml GetChildContent: @"RequestId"];
if (xml.LastMethodSuccess == YES) {
NSLog(@"%@%@",@"AWS request ID: ",value);
}
}
return;
}
if (success != YES) {
NSLog(@"%@",@"Invalid S3 XML response.");
return;
}
[stringCompare SetString: xml.Tag];
BOOL stringMatch9 = [stringCompare ContentsEqual: @"ListAllMyBucketsResult" caseSensitive: YES];
if (stringMatch9 != YES) {
NSLog(@"%@",@"Unexpected S3 response root.");
return;
}
if ([xml HasChildWithTag: @"Buckets"] != YES) {
NSLog(@"%@",@"Missing Buckets collection.");
return;
}
index = 0;
while ((index < [[xml NumChildrenAt: @"Buckets"] intValue])) {
xml.I = [NSNumber numberWithInt: index];
value = [xml GetChildContent: @"Buckets|Bucket[i]|Name"];
[stringCompare SetString: value];
BOOL stringMatch10 = [stringCompare ContentsEqual: @"" caseSensitive: YES];
if ((xml.LastMethodSuccess != YES) || (stringMatch10 == YES)) {
NSLog(@"%@",@"Missing or empty Buckets|Bucket[i]|Name.");
return;
}
NSLog(@"%@%@",@"Bucket: ",value);
index = index + 1;
}
continuation = @"";
if ([xml HasChildWithTag: @"ContinuationToken"] == YES) {
continuation = [xml GetChildContent: @"ContinuationToken"];
if (xml.LastMethodSuccess != YES) {
NSLog(@"%@",@"Invalid continuation token.");
return;
}
}
more = NO;
[stringCompare SetString: continuation];
BOOL stringMatch11 = [stringCompare ContentsEqual: @"" caseSensitive: YES];
if (stringMatch11 != YES) {
if ([seenTokens Contains: continuation] == YES) {
NSLog(@"%@",@"Repeated continuation token; enumeration is incomplete.");
return;
}
success = [seenTokens AddStr: continuation value: @"seen"];
if (success != YES) {
NSLog(@"%@",@"Could not track pagination.");
return;
}
more = YES;
}
}
NSLog(@"%@",@"Bucket enumeration complete.");