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 Lua Downloads
local chilkat = require("chilkat")
local stringCompare = chilkat.StringBuilder.new()
-- Assumes Chilkat is unlocked. See Global Unlock Sample.
-- Accept the private XML handoff from either GetSessionToken or AssumeRole.
local xmlToken = chilkat.Xml.new()
xmlToken.strict = true
local success = xmlToken:load_xml_file("qa_data/tokens/aws_session_token.xml")
if not success then
print("Could not load the private STS credential file.")
return
end
local credentialPath = ""
stringCompare:set_string(xmlToken.tag)
local stringMatch1 = stringCompare:contents_equal("GetSessionTokenResponse", true)
if stringMatch1 then
credentialPath = "GetSessionTokenResult|Credentials"
end
stringCompare:set_string(xmlToken.tag)
local stringMatch2 = stringCompare:contents_equal("AssumeRoleResponse", true)
if stringMatch2 then
credentialPath = "AssumeRoleResult|Credentials"
end
stringCompare:set_string(credentialPath)
local stringMatch3 = stringCompare:contents_equal("", true)
if stringMatch3 then
print("Expected a GetSessionToken or AssumeRole credential response.")
return
end
local path = chilkat.StringBuilder.new()
success = path:set_string(credentialPath)
if not success then
print("Could not build credential path.")
return
end
success = path:append("|AccessKeyId")
if not success then
print("Could not build credential path.")
return
end
local accessKey = xmlToken:get_child_content(path:get_as_string())
stringCompare:set_string(accessKey)
local stringMatch4 = stringCompare:contents_equal("", true)
if (not xmlToken.last_method_success) or (stringMatch4) then
print("Missing or empty AccessKeyId.")
return
end
success = path:set_string(credentialPath)
if not success then
print("Could not build credential path.")
return
end
success = path:append("|SecretAccessKey")
if not success then
print("Could not build credential path.")
return
end
local secretKey = xmlToken:get_child_content(path:get_as_string())
stringCompare:set_string(secretKey)
local stringMatch5 = stringCompare:contents_equal("", true)
if (not xmlToken.last_method_success) or (stringMatch5) then
print("Missing or empty SecretAccessKey.")
return
end
success = path:set_string(credentialPath)
if not success then
print("Could not build credential path.")
return
end
success = path:append("|SessionToken")
if not success then
print("Could not build credential path.")
return
end
local sessionToken = xmlToken:get_child_content(path:get_as_string())
stringCompare:set_string(sessionToken)
local stringMatch6 = stringCompare:contents_equal("", true)
if (not xmlToken.last_method_success) or (stringMatch6) then
print("Missing or empty SessionToken.")
return
end
success = path:set_string(credentialPath)
if not success then
print("Could not build credential path.")
return
end
success = path:append("|Expiration")
if not success then
print("Could not build credential path.")
return
end
local expiration = xmlToken:get_child_content(path:get_as_string())
stringCompare:set_string(expiration)
local stringMatch7 = stringCompare:contents_equal("", true)
if (not xmlToken.last_method_success) or (stringMatch7) then
print("Missing or empty Expiration.")
return
end
local expires = chilkat.DateTime.new()
local now = chilkat.DateTime.new()
success = expires:set_from_timestamp(expiration)
if not success then
print("Stored expiration is invalid.")
return
end
success = now:set_from_current_system_time()
if not success then
print("Could not read current time.")
return
end
if expires:diff_seconds(now) <= 60 then
print("Stored credentials are expired or expire within 60 seconds; obtain fresh credentials.")
return
end
-- This S3 region is independent of the region that issued the STS credentials.
local region = "us-west-2"
local endpoint = chilkat.StringBuilder.new()
endpoint:append("s3.")
endpoint:append(region)
endpoint:append(".amazonaws.com")
local aws = chilkat.AuthAws.new()
aws.access_key = accessKey
aws.secret_key = secretKey
aws.region = region
aws.service_name = "s3"
aws.signature_version = 4
local rest = chilkat.Rest.new()
rest.connect_timeout_ms = 20000
rest.idle_timeout_ms = 60000
rest.verbose_logging = false
success = rest:set_auth_aws(aws)
if not success then
print("Could not configure request signing.")
return
end
-- Keep this verified Socket alive while Rest uses its connection.
local connection = chilkat.Socket.new()
connection.require_ssl_cert_verify = true
connection.max_read_idle_ms = 60000
connection.max_send_idle_ms = 60000
success = connection:connect(endpoint:get_as_string(), 443, true, 20000)
if not success then
print("TLS connection failed; inspect diagnostics privately.")
return
end
success = rest:use_connection(connection, true)
if not success then
print("Could not attach TLS connection.")
return
end
local xml = chilkat.Xml.new()
xml.strict = true
local value = ""
local seenTokens = chilkat.Hashtable.new()
local continuation = ""
local responseXml = ""
local page = 0
local index = 0
local more = true
while more do
if page == 10000 then
print("Page bound reached; bucket enumeration is incomplete.")
return
end
success = now:set_from_current_system_time()
if not success then
print("Could not read current time.")
return
end
if expires:diff_seconds(now) <= 60 then
print("Credentials are expiring; obtain fresh credentials before continuing the listing.")
return
end
page = page + 1
success = rest:clear_all_query_params()
if not success then
print("Could not clear parameters from the previous page.")
return
end
-- All three credential components are required. Never log this signed URL.
success = rest:add_query_param("X-Amz-Security-Token", sessionToken)
if not success then
print("Could not set X-Amz-Security-Token.")
return
end
success = rest:add_query_param("max-buckets", "100")
if not success then
print("Could not set max-buckets.")
return
end
stringCompare:set_string(continuation)
local stringMatch8 = stringCompare:contents_equal("", true)
if not stringMatch8 then
success = rest:add_query_param("continuation-token", continuation)
if not success then
print("Could not set continuation-token.")
return
end
end
responseXml = rest:full_request_no_body("GET", "/")
if not rest.last_method_success then
print("S3 request did not complete; enumeration is incomplete.")
return
end
success = xml:load_xml(responseXml)
if rest.response_status_code ~= 200 then
print("S3 HTTP status: " .. rest.response_status_code)
if success then
value = xml:get_child_content("Code")
if xml.last_method_success then
print("AWS error code: " .. value)
end
value = xml:get_child_content("RequestId")
if xml.last_method_success then
print("AWS request ID: " .. value)
end
end
return
end
if not success then
print("Invalid S3 XML response.")
return
end
stringCompare:set_string(xml.tag)
local stringMatch9 = stringCompare:contents_equal("ListAllMyBucketsResult", true)
if not stringMatch9 then
print("Unexpected S3 response root.")
return
end
if not xml:has_child_with_tag("Buckets") then
print("Missing Buckets collection.")
return
end
index = 0
while index < xml:num_children_at("Buckets") do
xml.i = index
value = xml:get_child_content("Buckets|Bucket[i]|Name")
stringCompare:set_string(value)
local stringMatch10 = stringCompare:contents_equal("", true)
if (not xml.last_method_success) or (stringMatch10) then
print("Missing or empty Buckets|Bucket[i]|Name.")
return
end
print("Bucket: " .. value)
index = index + 1
end
continuation = ""
if xml:has_child_with_tag("ContinuationToken") then
continuation = xml:get_child_content("ContinuationToken")
if not xml.last_method_success then
print("Invalid continuation token.")
return
end
end
more = false
stringCompare:set_string(continuation)
local stringMatch11 = stringCompare:contents_equal("", true)
if not stringMatch11 then
if seenTokens:contains(continuation) then
print("Repeated continuation token; enumeration is incomplete.")
return
end
success = seenTokens:add_str(continuation, "seen")
if not success then
print("Could not track pagination.")
return
end
more = true
end
end
print("Bucket enumeration complete.")