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 Dart Downloads
import 'package:chilkat/chilkat.dart';
void main() {
var success = false;
final stringCompare = CkStringBuilder();
// Assumes Chilkat is unlocked. See Global Unlock Sample.
// Accept the private XML handoff from either GetSessionToken or AssumeRole.
final xmlToken = CkXml();
xmlToken.strict = true;
success = true;
try {
xmlToken.loadXmlFile('qa_data/tokens/aws_session_token.xml');
} on ChilkatException {
success = false;
}
if (!success) {
print('Could not load the private STS credential file.');
return;
}
var credentialPath = '';
stringCompare.setString(xmlToken.tag);
final stringMatch1 = stringCompare.contentsEqual('GetSessionTokenResponse', true);
if (stringMatch1) {
credentialPath = 'GetSessionTokenResult|Credentials';
}
stringCompare.setString(xmlToken.tag);
final stringMatch2 = stringCompare.contentsEqual('AssumeRoleResponse', true);
if (stringMatch2) {
credentialPath = 'AssumeRoleResult|Credentials';
}
stringCompare.setString(credentialPath);
final stringMatch3 = stringCompare.contentsEqual('', true);
if (stringMatch3) {
print('Expected a GetSessionToken or AssumeRole credential response.');
return;
}
final path = CkStringBuilder();
success = true;
try {
path.setString(credentialPath);
} on ChilkatException {
success = false;
}
if (!success) {
print('Could not build credential path.');
return;
}
success = true;
try {
path.append('|AccessKeyId');
} on ChilkatException {
success = false;
}
if (!success) {
print('Could not build credential path.');
return;
}
final accessKey = xmlToken.getChildContent(path.getAsString());
stringCompare.setString(accessKey);
final stringMatch4 = stringCompare.contentsEqual('', true);
if ((!xmlToken.lastMethodSuccess) || (stringMatch4)) {
print('Missing or empty AccessKeyId.');
return;
}
success = true;
try {
path.setString(credentialPath);
} on ChilkatException {
success = false;
}
if (!success) {
print('Could not build credential path.');
return;
}
success = true;
try {
path.append('|SecretAccessKey');
} on ChilkatException {
success = false;
}
if (!success) {
print('Could not build credential path.');
return;
}
final secretKey = xmlToken.getChildContent(path.getAsString());
stringCompare.setString(secretKey);
final stringMatch5 = stringCompare.contentsEqual('', true);
if ((!xmlToken.lastMethodSuccess) || (stringMatch5)) {
print('Missing or empty SecretAccessKey.');
return;
}
success = true;
try {
path.setString(credentialPath);
} on ChilkatException {
success = false;
}
if (!success) {
print('Could not build credential path.');
return;
}
success = true;
try {
path.append('|SessionToken');
} on ChilkatException {
success = false;
}
if (!success) {
print('Could not build credential path.');
return;
}
final sessionToken = xmlToken.getChildContent(path.getAsString());
stringCompare.setString(sessionToken);
final stringMatch6 = stringCompare.contentsEqual('', true);
if ((!xmlToken.lastMethodSuccess) || (stringMatch6)) {
print('Missing or empty SessionToken.');
return;
}
success = true;
try {
path.setString(credentialPath);
} on ChilkatException {
success = false;
}
if (!success) {
print('Could not build credential path.');
return;
}
success = true;
try {
path.append('|Expiration');
} on ChilkatException {
success = false;
}
if (!success) {
print('Could not build credential path.');
return;
}
final expiration = xmlToken.getChildContent(path.getAsString());
stringCompare.setString(expiration);
final stringMatch7 = stringCompare.contentsEqual('', true);
if ((!xmlToken.lastMethodSuccess) || (stringMatch7)) {
print('Missing or empty Expiration.');
return;
}
final expires = CkDateTime();
final now = CkDateTime();
success = true;
try {
expires.setFromTimestamp(expiration);
} on ChilkatException {
success = false;
}
if (!success) {
print('Stored expiration is invalid.');
return;
}
success = true;
try {
now.setFromCurrentSystemTime();
} on ChilkatException {
success = false;
}
if (!success) {
print('Could not read current time.');
return;
}
if (expires.diffSeconds(now) <= 60) {
print('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.
final region = 'us-west-2';
final endpoint = CkStringBuilder();
endpoint.append('s3.');
endpoint.append(region);
endpoint.append('.amazonaws.com');
final aws = CkAuthAws();
aws.accessKey = accessKey;
aws.secretKey = secretKey;
aws.region = region;
aws.serviceName = 's3';
aws.signatureVersion = 4;
final rest = CkRest();
rest.connectTimeoutMs = 20000;
rest.idleTimeoutMs = 60000;
rest.verboseLogging = false;
success = true;
try {
rest.setAuthAws(aws);
} on ChilkatException {
success = false;
}
if (!success) {
print('Could not configure request signing.');
return;
}
// Keep this verified Socket alive while Rest uses its connection.
final connection = CkSocket();
connection.requireSslCertVerify = true;
connection.maxReadIdleMs = 60000;
connection.maxSendIdleMs = 60000;
success = true;
try {
connection.connect(endpoint.getAsString(), 443, true, 20000);
} on ChilkatException {
success = false;
}
if (!success) {
print('TLS connection failed; inspect diagnostics privately.');
return;
}
success = true;
try {
rest.useConnection(connection, true);
} on ChilkatException {
success = false;
}
if (!success) {
print('Could not attach TLS connection.');
return;
}
final xml = CkXml();
xml.strict = true;
var value = '';
final seenTokens = CkHashtable();
var continuation = '';
var responseXml = '';
var page = 0;
var index = 0;
var more = true;
while (more) {
if (page == 10000) {
print('Page bound reached; bucket enumeration is incomplete.');
return;
}
success = true;
try {
now.setFromCurrentSystemTime();
} on ChilkatException {
success = false;
}
if (!success) {
print('Could not read current time.');
return;
}
if (expires.diffSeconds(now) <= 60) {
print('Credentials are expiring; obtain fresh credentials before continuing the listing.');
return;
}
page++;
success = true;
try {
rest.clearAllQueryParams();
} on ChilkatException {
success = false;
}
if (!success) {
print('Could not clear parameters from the previous page.');
return;
}
// All three credential components are required. Never log this signed URL.
success = true;
try {
rest.addQueryParam('X-Amz-Security-Token', sessionToken);
} on ChilkatException {
success = false;
}
if (!success) {
print('Could not set X-Amz-Security-Token.');
return;
}
success = true;
try {
rest.addQueryParam('max-buckets', '100');
} on ChilkatException {
success = false;
}
if (!success) {
print('Could not set max-buckets.');
return;
}
stringCompare.setString(continuation);
final stringMatch8 = stringCompare.contentsEqual('', true);
if (!stringMatch8) {
success = true;
try {
rest.addQueryParam('continuation-token', continuation);
} on ChilkatException {
success = false;
}
if (!success) {
print('Could not set continuation-token.');
return;
}
}
try {
responseXml = rest.fullRequestNoBody('GET', '/');
} on ChilkatException {
print('S3 request did not complete; enumeration is incomplete.');
return;
}
success = true;
try {
xml.loadXml(responseXml);
} on ChilkatException {
success = false;
}
if (rest.responseStatusCode != 200) {
print('S3 HTTP status: ${rest.responseStatusCode}');
if (success) {
try {
value = xml.getChildContent('Code');
print('AWS error code: $value');
} on ChilkatException {
// xml.getChildContent() failed; continue anyway.
}
try {
value = xml.getChildContent('RequestId');
print('AWS request ID: $value');
} on ChilkatException {
// xml.getChildContent() failed; continue anyway.
}
}
return;
}
if (!success) {
print('Invalid S3 XML response.');
return;
}
stringCompare.setString(xml.tag);
final stringMatch9 = stringCompare.contentsEqual('ListAllMyBucketsResult', true);
if (!stringMatch9) {
print('Unexpected S3 response root.');
return;
}
if (!xml.hasChildWithTag('Buckets')) {
print('Missing Buckets collection.');
return;
}
index = 0;
while (index < xml.numChildrenAt('Buckets')) {
xml.i = index;
value = xml.getChildContent('Buckets|Bucket[i]|Name');
stringCompare.setString(value);
final stringMatch10 = stringCompare.contentsEqual('', true);
if ((!xml.lastMethodSuccess) || (stringMatch10)) {
print('Missing or empty Buckets|Bucket[i]|Name.');
return;
}
print('Bucket: $value');
index++;
}
continuation = '';
if (xml.hasChildWithTag('ContinuationToken')) {
try {
continuation = xml.getChildContent('ContinuationToken');
} on ChilkatException {
print('Invalid continuation token.');
return;
}
}
more = false;
stringCompare.setString(continuation);
final stringMatch11 = stringCompare.contentsEqual('', true);
if (!stringMatch11) {
if (seenTokens.contains(continuation)) {
print('Repeated continuation token; enumeration is incomplete.');
return;
}
success = true;
try {
seenTokens.addStr(continuation, 'seen');
} on ChilkatException {
success = false;
}
if (!success) {
print('Could not track pagination.');
return;
}
more = true;
}
}
print('Bucket enumeration complete.');
}