Sample code for 30+ languages & platforms
Python 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 Python Downloads

Python
import sys
import chilkat2

success = False

stringCompare = chilkat2.StringBuilder()
# Assumes Chilkat is unlocked. See Global Unlock Sample.
# Accept the private XML handoff from either GetSessionToken or AssumeRole.
xmlToken = chilkat2.Xml()
xmlToken.Strict = True
success = xmlToken.LoadXmlFile("qa_data/tokens/aws_session_token.xml")
if (success != True):
    print("Could not load the private STS credential file.")
    sys.exit()

credentialPath = ""
stringCompare.SetString(xmlToken.Tag)
stringMatch1 = stringCompare.ContentsEqual("GetSessionTokenResponse",True)
if (stringMatch1 == True):
    credentialPath = "GetSessionTokenResult|Credentials"

stringCompare.SetString(xmlToken.Tag)
stringMatch2 = stringCompare.ContentsEqual("AssumeRoleResponse",True)
if (stringMatch2 == True):
    credentialPath = "AssumeRoleResult|Credentials"

stringCompare.SetString(credentialPath)
stringMatch3 = stringCompare.ContentsEqual("",True)
if (stringMatch3 == True):
    print("Expected a GetSessionToken or AssumeRole credential response.")
    sys.exit()

path = chilkat2.StringBuilder()
success = path.SetString(credentialPath)
if (success != True):
    print("Could not build credential path.")
    sys.exit()

success = path.Append("|AccessKeyId")
if (success != True):
    print("Could not build credential path.")
    sys.exit()

accessKey = xmlToken.GetChildContent(path.GetAsString())
stringCompare.SetString(accessKey)
stringMatch4 = stringCompare.ContentsEqual("",True)
if ((xmlToken.LastMethodSuccess != True) or (stringMatch4 == True)):
    print("Missing or empty AccessKeyId.")
    sys.exit()

success = path.SetString(credentialPath)
if (success != True):
    print("Could not build credential path.")
    sys.exit()

success = path.Append("|SecretAccessKey")
if (success != True):
    print("Could not build credential path.")
    sys.exit()

secretKey = xmlToken.GetChildContent(path.GetAsString())
stringCompare.SetString(secretKey)
stringMatch5 = stringCompare.ContentsEqual("",True)
if ((xmlToken.LastMethodSuccess != True) or (stringMatch5 == True)):
    print("Missing or empty SecretAccessKey.")
    sys.exit()

success = path.SetString(credentialPath)
if (success != True):
    print("Could not build credential path.")
    sys.exit()

success = path.Append("|SessionToken")
if (success != True):
    print("Could not build credential path.")
    sys.exit()

sessionToken = xmlToken.GetChildContent(path.GetAsString())
stringCompare.SetString(sessionToken)
stringMatch6 = stringCompare.ContentsEqual("",True)
if ((xmlToken.LastMethodSuccess != True) or (stringMatch6 == True)):
    print("Missing or empty SessionToken.")
    sys.exit()

success = path.SetString(credentialPath)
if (success != True):
    print("Could not build credential path.")
    sys.exit()

success = path.Append("|Expiration")
if (success != True):
    print("Could not build credential path.")
    sys.exit()

expiration = xmlToken.GetChildContent(path.GetAsString())
stringCompare.SetString(expiration)
stringMatch7 = stringCompare.ContentsEqual("",True)
if ((xmlToken.LastMethodSuccess != True) or (stringMatch7 == True)):
    print("Missing or empty Expiration.")
    sys.exit()

expires = chilkat2.CkDateTime()
now = chilkat2.CkDateTime()
success = expires.SetFromTimestamp(expiration)
if (success != True):
    print("Stored expiration is invalid.")
    sys.exit()

success = now.SetFromCurrentSystemTime()
if (success != True):
    print("Could not read current time.")
    sys.exit()

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

# This S3 region is independent of the region that issued the STS credentials.
region = "us-west-2"
endpoint = chilkat2.StringBuilder()
endpoint.Append("s3.")
endpoint.Append(region)
endpoint.Append(".amazonaws.com")
aws = chilkat2.AuthAws()
aws.AccessKey = accessKey
aws.SecretKey = secretKey
aws.Region = region
aws.ServiceName = "s3"
aws.SignatureVersion = 4
rest = chilkat2.Rest()
rest.ConnectTimeoutMs = 20000
rest.IdleTimeoutMs = 60000
rest.VerboseLogging = False
success = rest.SetAuthAws(aws)
if (success != True):
    print("Could not configure request signing.")
    sys.exit()

# Keep this verified Socket alive while Rest uses its connection.
connection = chilkat2.Socket()
connection.RequireSslCertVerify = True
connection.MaxReadIdleMs = 60000
connection.MaxSendIdleMs = 60000
success = connection.Connect(endpoint.GetAsString(),443,True,20000)
if (success != True):
    print("TLS connection failed; inspect diagnostics privately.")
    sys.exit()

success = rest.UseConnection(connection,True)
if (success != True):
    print("Could not attach TLS connection.")
    sys.exit()

xml = chilkat2.Xml()
xml.Strict = True

seenTokens = chilkat2.Hashtable()
continuation = ""

page = 0

more = True
while (more == True) :
    if (page == 10000):
        print("Page bound reached; bucket enumeration is incomplete.")
        sys.exit()

    success = now.SetFromCurrentSystemTime()
    if (success != True):
        print("Could not read current time.")
        sys.exit()

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

    page = page + 1
    success = rest.ClearAllQueryParams()
    if (success != True):
        print("Could not clear parameters from the previous page.")
        sys.exit()

    # 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.")
        sys.exit()

    success = rest.AddQueryParam("max-buckets","100")
    if (success != True):
        print("Could not set max-buckets.")
        sys.exit()

    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.")
            sys.exit()

    responseXml = rest.FullRequestNoBody("GET","/")
    if (rest.LastMethodSuccess != True):
        print("S3 request did not complete; enumeration is incomplete.")
        sys.exit()

    success = xml.LoadXml(responseXml)
    if (rest.ResponseStatusCode != 200):
        print("S3 HTTP status: " + str(rest.ResponseStatusCode))
        if (success == True):
            value = xml.GetChildContent("Code")
            if (xml.LastMethodSuccess == True):
                print("AWS error code: " + value)

            value = xml.GetChildContent("RequestId")
            if (xml.LastMethodSuccess == True):
                print("AWS request ID: " + value)

        sys.exit()

    if (success != True):
        print("Invalid S3 XML response.")
        sys.exit()

    stringCompare.SetString(xml.Tag)
    stringMatch9 = stringCompare.ContentsEqual("ListAllMyBucketsResult",True)
    if (stringMatch9 != True):
        print("Unexpected S3 response root.")
        sys.exit()

    if (xml.HasChildWithTag("Buckets") != True):
        print("Missing Buckets collection.")
        sys.exit()

    index = 0
    while (index < xml.NumChildrenAt("Buckets")) :
        xml.I = index
        value = xml.GetChildContent("Buckets|Bucket[i]|Name")
        stringCompare.SetString(value)
        stringMatch10 = stringCompare.ContentsEqual("",True)
        if ((xml.LastMethodSuccess != True) or (stringMatch10 == True)):
            print("Missing or empty Buckets|Bucket[i]|Name.")
            sys.exit()

        print("Bucket: " + value)
        index = index + 1

    continuation = ""
    if (xml.HasChildWithTag("ContinuationToken") == True):
        continuation = xml.GetChildContent("ContinuationToken")
        if (xml.LastMethodSuccess != True):
            print("Invalid continuation token.")
            sys.exit()

    more = False
    stringCompare.SetString(continuation)
    stringMatch11 = stringCompare.ContentsEqual("",True)
    if (stringMatch11 != True):
        if (seenTokens.Contains(continuation) == True):
            print("Repeated continuation token; enumeration is incomplete.")
            sys.exit()

        success = seenTokens.AddStr(continuation,"seen")
        if (success != True):
            print("Could not track pagination.")
            sys.exit()

        more = True

print("Bucket enumeration complete.")