Sample code for 30+ languages & platforms
Ruby Requires Chilkat v11.6.0+

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.

AWS API reference

Chilkat Ruby Downloads

Ruby
require 'chilkat'

success = false

stringCompare = Chilkat::CkStringBuilder.new()
#  Assumes Chilkat is unlocked. See Global Unlock Sample.
#  Accept the private XML handoff from either GetSessionToken or AssumeRole.
xmlToken = Chilkat::CkXml.new()
xmlToken.put_Strict(true)
success = xmlToken.LoadXmlFile("qa_data/tokens/aws_session_token.xml")
if (success != true)
    print "Could not load the private STS credential file." + "\n";
    exit
end

credentialPath = ""
stringCompare.SetString(xmlToken.tag())
stringMatch1 = stringCompare.ContentsEqual("GetSessionTokenResponse",true)
if (stringMatch1 == true)
    credentialPath = "GetSessionTokenResult|Credentials"
end

stringCompare.SetString(xmlToken.tag())
stringMatch2 = stringCompare.ContentsEqual("AssumeRoleResponse",true)
if (stringMatch2 == true)
    credentialPath = "AssumeRoleResult|Credentials"
end

stringCompare.SetString(credentialPath)
stringMatch3 = stringCompare.ContentsEqual("",true)
if (stringMatch3 == true)
    print "Expected a GetSessionToken or AssumeRole credential response." + "\n";
    exit
end

path = Chilkat::CkStringBuilder.new()
success = path.SetString(credentialPath)
if (success != true)
    print "Could not build credential path." + "\n";
    exit
end

success = path.Append("|AccessKeyId")
if (success != true)
    print "Could not build credential path." + "\n";
    exit
end

accessKey = xmlToken.getChildContent(path.getAsString())
stringCompare.SetString(accessKey)
stringMatch4 = stringCompare.ContentsEqual("",true)
if ((xmlToken.get_LastMethodSuccess() != true) or (stringMatch4 == true))
    print "Missing or empty AccessKeyId." + "\n";
    exit
end

success = path.SetString(credentialPath)
if (success != true)
    print "Could not build credential path." + "\n";
    exit
end

success = path.Append("|SecretAccessKey")
if (success != true)
    print "Could not build credential path." + "\n";
    exit
end

secretKey = xmlToken.getChildContent(path.getAsString())
stringCompare.SetString(secretKey)
stringMatch5 = stringCompare.ContentsEqual("",true)
if ((xmlToken.get_LastMethodSuccess() != true) or (stringMatch5 == true))
    print "Missing or empty SecretAccessKey." + "\n";
    exit
end

success = path.SetString(credentialPath)
if (success != true)
    print "Could not build credential path." + "\n";
    exit
end

success = path.Append("|SessionToken")
if (success != true)
    print "Could not build credential path." + "\n";
    exit
end

sessionToken = xmlToken.getChildContent(path.getAsString())
stringCompare.SetString(sessionToken)
stringMatch6 = stringCompare.ContentsEqual("",true)
if ((xmlToken.get_LastMethodSuccess() != true) or (stringMatch6 == true))
    print "Missing or empty SessionToken." + "\n";
    exit
end

success = path.SetString(credentialPath)
if (success != true)
    print "Could not build credential path." + "\n";
    exit
end

success = path.Append("|Expiration")
if (success != true)
    print "Could not build credential path." + "\n";
    exit
end

expiration = xmlToken.getChildContent(path.getAsString())
stringCompare.SetString(expiration)
stringMatch7 = stringCompare.ContentsEqual("",true)
if ((xmlToken.get_LastMethodSuccess() != true) or (stringMatch7 == true))
    print "Missing or empty Expiration." + "\n";
    exit
end

expires = Chilkat::CkDateTime.new()
now = Chilkat::CkDateTime.new()
success = expires.SetFromTimestamp(expiration)
if (success != true)
    print "Stored expiration is invalid." + "\n";
    exit
end

success = now.SetFromCurrentSystemTime()
if (success != true)
    print "Could not read current time." + "\n";
    exit
end

if (expires.DiffSeconds(now) <= 60)
    print "Stored credentials are expired or expire within 60 seconds; obtain fresh credentials." + "\n";
    exit
end

#  This S3 region is independent of the region that issued the STS credentials.
region = "us-west-2"
endpoint = Chilkat::CkStringBuilder.new()
endpoint.Append("s3.")
endpoint.Append(region)
endpoint.Append(".amazonaws.com")
aws = Chilkat::CkAuthAws.new()
aws.put_AccessKey(accessKey)
aws.put_SecretKey(secretKey)
aws.put_Region(region)
aws.put_ServiceName("s3")
aws.put_SignatureVersion(4)
rest = Chilkat::CkRest.new()
rest.put_ConnectTimeoutMs(20000)
rest.put_IdleTimeoutMs(60000)
rest.put_VerboseLogging(false)
success = rest.SetAuthAws(aws)
if (success != true)
    print "Could not configure request signing." + "\n";
    exit
end

#  Keep this verified Socket alive while Rest uses its connection.
connection = Chilkat::CkSocket.new()
connection.put_RequireSslCertVerify(true)
connection.put_MaxReadIdleMs(60000)
connection.put_MaxSendIdleMs(60000)
success = connection.Connect(endpoint.getAsString(),443,true,20000)
if (success != true)
    print "TLS connection failed; inspect diagnostics privately." + "\n";
    exit
end

success = rest.UseConnection(connection,true)
if (success != true)
    print "Could not attach TLS connection." + "\n";
    exit
end

xml = Chilkat::CkXml.new()
xml.put_Strict(true)

seenTokens = Chilkat::CkHashtable.new()
continuation = ""

page = 0

more = true
while (more == true)
    if (page == 10000)
        print "Page bound reached; bucket enumeration is incomplete." + "\n";
        exit
    end

    success = now.SetFromCurrentSystemTime()
    if (success != true)
        print "Could not read current time." + "\n";
        exit
    end

    if (expires.DiffSeconds(now) <= 60)
        print "Credentials are expiring; obtain fresh credentials before continuing the listing." + "\n";
        exit
    end

    page = page + 1
    success = rest.ClearAllQueryParams()
    if (success != true)
        print "Could not clear parameters from the previous page." + "\n";
        exit
    end

    #  All three credential components are required. Never log this signed URL.
    success = rest.AddQueryParam("X-Amz-Security-Token",sessionToken)
    if (success != true)
        print "Could not set X-Amz-Security-Token." + "\n";
        exit
    end

    success = rest.AddQueryParam("max-buckets","100")
    if (success != true)
        print "Could not set max-buckets." + "\n";
        exit
    end

    stringCompare.SetString(continuation)
    stringMatch8 = stringCompare.ContentsEqual("",true)
    if (stringMatch8 != true)
        success = rest.AddQueryParam("continuation-token",continuation)
        if (success != true)
            print "Could not set continuation-token." + "\n";
            exit
        end

    end

    responseXml = rest.fullRequestNoBody("GET","/")
    if (rest.get_LastMethodSuccess() != true)
        print "S3 request did not complete; enumeration is incomplete." + "\n";
        exit
    end

    success = xml.LoadXml(responseXml)
    if (rest.get_ResponseStatusCode() != 200)
        print "S3 HTTP status: " + rest.get_ResponseStatusCode().to_s() + "\n";
        if (success == true)
            value = xml.getChildContent("Code")
            if (xml.get_LastMethodSuccess() == true)
                print "AWS error code: " + value + "\n";
            end

            value = xml.getChildContent("RequestId")
            if (xml.get_LastMethodSuccess() == true)
                print "AWS request ID: " + value + "\n";
            end

        end

        exit
    end

    if (success != true)
        print "Invalid S3 XML response." + "\n";
        exit
    end

    stringCompare.SetString(xml.tag())
    stringMatch9 = stringCompare.ContentsEqual("ListAllMyBucketsResult",true)
    if (stringMatch9 != true)
        print "Unexpected S3 response root." + "\n";
        exit
    end

    if (xml.HasChildWithTag("Buckets") != true)
        print "Missing Buckets collection." + "\n";
        exit
    end

    index = 0
    while (index < xml.NumChildrenAt("Buckets"))
        xml.put_I(index)
        value = xml.getChildContent("Buckets|Bucket[i]|Name")
        stringCompare.SetString(value)
        stringMatch10 = stringCompare.ContentsEqual("",true)
        if ((xml.get_LastMethodSuccess() != true) or (stringMatch10 == true))
            print "Missing or empty Buckets|Bucket[i]|Name." + "\n";
            exit
        end

        print "Bucket: " + value + "\n";
        index = index + 1
    end
    continuation = ""
    if (xml.HasChildWithTag("ContinuationToken") == true)
        continuation = xml.getChildContent("ContinuationToken")
        if (xml.get_LastMethodSuccess() != true)
            print "Invalid continuation token." + "\n";
            exit
        end

    end

    more = false
    stringCompare.SetString(continuation)
    stringMatch11 = stringCompare.ContentsEqual("",true)
    if (stringMatch11 != true)
        if (seenTokens.Contains(continuation) == true)
            print "Repeated continuation token; enumeration is incomplete." + "\n";
            exit
        end

        success = seenTokens.AddStr(continuation,"seen")
        if (success != true)
            print "Could not track pagination." + "\n";
            exit
        end

        more = true
    end

end
print "Bucket enumeration complete." + "\n";