AWS STS: Assume a Role for S3 Bucket Listing
See more AWS Security Token Service Examples
Uses Chilkat.Rest and AuthAws with AWS Signature Version 4. STS uses the Query API version 2011-06-15; that version date is still current. The examples send URL-encoded POST forms rather than operation parameters in a GET URL. They use the commercial-partition regional endpoint sts.us-west-2.amazonaws.com and matching signing region/service sts, with explicit TLS certificate verification. Choose the appropriate region/partition endpoint for your deployment.
Load private qa_data/aws/sts.json with nonempty string fields access_key and secret_key. These examples do not discover credentials, assume roles implicitly, or refresh credentials automatically. No access key, secret key, token, full XML response or diagnostic dump is printed.
Both credential-producing examples retain the existing handoff file qa_data/tokens/aws_session_token.xml. It contains plaintext credentials: pre-create a private directory with restrictive OS permissions and keep it out of web roots, source control, shared logs and shared storage. The sample checks the write, but does not set ACLs, encrypt the file, perform atomic replacement, or coordinate concurrent writers. Prefer in-memory handoff or an appropriate credential store in production. A failed request can leave an older file in place; do not assume a failed run refreshed it. The consumer validates expiration, allowing a 60-second margin.
Set role_arn and role_session_name in the private configuration. Names must contain 2–64 allowed characters. The target trust policy and applicable caller authorization must permit AssumeRole. The sample's session policy permits only s3:ListAllMyBuckets, intersected with the role's permissions, for use by the companion S3 listing example; it cannot elevate the role's access. Other policy types, denies and resource-based rules still participate in authorization.
The fixed 3600-second request works within the one-hour role-chaining ceiling and must still fit the role's configured maximum. For temporary source credentials, also provide nonempty session_token and ISO 8601 expiration. The token is included in the signed form body. Optional external_id must be the value agreed with the role owner; it is not a password. Optional source_identity is subject to AWS syntax, trust conditions and sts:SetSourceIdentity permission. Optional MFA uses mfa_serial/mfa_code as a pair. These optional values must satisfy the actual trust policy.
This focused example omits managed session policies and session tags. When adding them, configure the required policies and tagging permissions, and account for inherited transitive tags during role chaining. STS session-token sizes are variable; preserve the complete value without a fixed buffer or truncation.
Chilkat Lua Downloads
local chilkat = require("chilkat")
local stringCompare = chilkat.StringBuilder.new()
-- Assumes Chilkat is unlocked. See Global Unlock Sample.
-- Keep this file private and outside public web content/source control.
local credentials = chilkat.JsonObject.new()
credentials.strict = true
local success = credentials:load_file("qa_data/aws/sts.json")
if not success then
print("Could not load private STS configuration.")
return
end
stringCompare:set_string(credentials:string_of("access_key"))
local stringMatch1 = stringCompare:contents_equal("", true)
if (credentials:json_type_of("access_key") ~= 1) or (stringMatch1) then
print("Missing or invalid access_key.")
return
end
stringCompare:set_string(credentials:string_of("secret_key"))
local stringMatch2 = stringCompare:contents_equal("", true)
if (credentials:json_type_of("secret_key") ~= 1) or (stringMatch2) then
print("Missing or invalid secret_key.")
return
end
local expires = chilkat.DateTime.new()
local now = chilkat.DateTime.new()
local region = "us-west-2"
if credentials:has_member("session_token") then
stringCompare:set_string(credentials:string_of("session_token"))
local stringMatch3 = stringCompare:contents_equal("", true)
if (credentials:json_type_of("session_token") ~= 1) or (stringMatch3) then
print("Missing or invalid session_token.")
return
end
stringCompare:set_string(credentials:string_of("expiration"))
local stringMatch4 = stringCompare:contents_equal("", true)
if (credentials:json_type_of("expiration") ~= 1) or (stringMatch4) then
print("Missing or invalid expiration.")
return
end
success = expires:set_from_timestamp(credentials:string_of("expiration"))
if not success then
print("Source 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("Source credentials are expired or expire within 60 seconds; obtain fresh credentials.")
return
end
end
stringCompare:set_string(credentials:string_of("role_arn"))
local stringMatch5 = stringCompare:contents_equal("", true)
if (credentials:json_type_of("role_arn") ~= 1) or (stringMatch5) then
print("Missing or invalid role_arn.")
return
end
stringCompare:set_string(credentials:string_of("role_session_name"))
local stringMatch6 = stringCompare:contents_equal("", true)
if (credentials:json_type_of("role_session_name") ~= 1) or (stringMatch6) then
print("Missing or invalid role_session_name.")
return
end
local identifier = chilkat.StringBuilder.new()
identifier:append(credentials:string_of("role_session_name"))
if (identifier.length < 2) or (identifier.length > 64) then
print("role_session_name must have 2-64 characters.")
return
end
local allowed = chilkat.StringBuilder.new()
allowed:append("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_+=,.@-")
local charIndex = 0
while charIndex < identifier.length do
if not allowed:contains(identifier:get_range(charIndex, 1, false), true) then
print("Invalid character in role_session_name.")
return
end
charIndex = charIndex + 1
end
local roleArn = chilkat.StringBuilder.new()
roleArn:append(credentials:string_of("role_arn"))
if (not roleArn:starts_with("arn:aws:iam::", true)) or (not roleArn:contains(":role/", true)) then
print("Use an IAM role ARN in the commercial AWS partition.")
return
end
if credentials:has_member("external_id") then
stringCompare:set_string(credentials:string_of("external_id"))
local stringMatch7 = stringCompare:contents_equal("", true)
if (credentials:json_type_of("external_id") ~= 1) or (stringMatch7) then
print("Missing or invalid external_id.")
return
end
end
if credentials:has_member("source_identity") then
stringCompare:set_string(credentials:string_of("source_identity"))
local stringMatch8 = stringCompare:contents_equal("", true)
if (credentials:json_type_of("source_identity") ~= 1) or (stringMatch8) then
print("Missing or invalid source_identity.")
return
end
end
-- MFA fields are optional as a pair. Preserve a leading zero in the code.
if (credentials:has_member("mfa_serial")) or (credentials:has_member("mfa_code")) then
stringCompare:set_string(credentials:string_of("mfa_serial"))
local stringMatch9 = stringCompare:contents_equal("", true)
if (credentials:json_type_of("mfa_serial") ~= 1) or (stringMatch9) then
print("Missing or invalid mfa_serial.")
return
end
stringCompare:set_string(credentials:string_of("mfa_code"))
local stringMatch10 = stringCompare:contents_equal("", true)
if (credentials:json_type_of("mfa_code") ~= 1) or (stringMatch10) then
print("Missing or invalid mfa_code.")
return
end
local mfaCode = chilkat.StringBuilder.new()
mfaCode:append(credentials:string_of("mfa_code"))
if mfaCode.length ~= 6 then
print("mfa_code must be a six-digit string.")
return
end
local digits = chilkat.StringBuilder.new()
digits:append("0123456789")
local digitIndex = 0
while digitIndex < 6 do
if not digits:contains(mfaCode:get_range(digitIndex, 1, false), true) then
print("mfa_code must contain only ASCII digits.")
return
end
digitIndex = digitIndex + 1
end
end
local endpoint = chilkat.StringBuilder.new()
endpoint:append("sts.")
endpoint:append(region)
endpoint:append(".amazonaws.com")
local aws = chilkat.AuthAws.new()
aws.access_key = credentials:string_of("access_key")
aws.secret_key = credentials:string_of("secret_key")
aws.region = region
aws.service_name = "sts"
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 = ""
success = rest:clear_all_query_params()
if not success then
print("Could not clear request parameters.")
return
end
success = rest:add_query_param("Action", "AssumeRole")
if not success then
print("Could not set Action.")
return
end
success = rest:add_query_param("Version", "2011-06-15")
if not success then
print("Could not set Version.")
return
end
success = rest:add_query_param("DurationSeconds", "3600")
if not success then
print("Could not set DurationSeconds.")
return
end
if credentials:has_member("session_token") then
success = rest:add_query_param("X-Amz-Security-Token", credentials:string_of("session_token"))
if not success then
print("Could not set X-Amz-Security-Token.")
return
end
end
success = rest:add_query_param("RoleArn", credentials:string_of("role_arn"))
if not success then
print("Could not set RoleArn.")
return
end
success = rest:add_query_param("RoleSessionName", credentials:string_of("role_session_name"))
if not success then
print("Could not set RoleSessionName.")
return
end
-- A session policy only restricts the role; it cannot add permissions.
local policy = chilkat.JsonObject.new()
success = policy:update_string("Version", "2012-10-17")
if not success then
print("Could not set policy version.")
return
end
success = policy:update_string("Statement[0].Effect", "Allow")
if not success then
print("Could not set policy effect.")
return
end
success = policy:update_string("Statement[0].Action", "s3:ListAllMyBuckets")
if not success then
print("Could not set policy action.")
return
end
success = policy:update_string("Statement[0].Resource", "*")
if not success then
print("Could not set policy resource.")
return
end
success = rest:add_query_param("Policy", policy:emit())
if not success then
print("Could not set Policy.")
return
end
if credentials:has_member("external_id") then
success = rest:add_query_param("ExternalId", credentials:string_of("external_id"))
if not success then
print("Could not set ExternalId.")
return
end
end
if credentials:has_member("source_identity") then
success = rest:add_query_param("SourceIdentity", credentials:string_of("source_identity"))
if not success then
print("Could not set SourceIdentity.")
return
end
end
if credentials:has_member("mfa_serial") then
success = rest:add_query_param("SerialNumber", credentials:string_of("mfa_serial"))
if not success then
print("Could not set SerialNumber.")
return
end
success = rest:add_query_param("TokenCode", credentials:string_of("mfa_code"))
if not success then
print("Could not set TokenCode.")
return
end
end
local responseXml = rest:full_request_form_url_encoded("POST", "/")
if not rest.last_method_success then
print("STS request did not complete; no credentials were saved. Inspect diagnostics privately.")
return
end
success = xml:load_xml(responseXml)
if rest.response_status_code ~= 200 then
print("STS HTTP status: " .. rest.response_status_code)
if success then
value = xml:get_child_content("Error|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
-- Full bodies, headers, and diagnostics can contain sensitive data.
return
end
if not success then
print("Invalid STS XML response; no credentials were saved.")
return
end
stringCompare:set_string(xml.tag)
local stringMatch11 = stringCompare:contents_equal("AssumeRoleResponse", true)
if not stringMatch11 then
print("Unexpected STS response root.")
return
end
value = xml:get_child_content("ResponseMetadata|RequestId")
stringCompare:set_string(value)
local stringMatch12 = stringCompare:contents_equal("", true)
if (not xml.last_method_success) or (stringMatch12) then
print("Missing or empty ResponseMetadata|RequestId.")
return
end
print("AWS request ID: " .. value)
local accessKey = xml:get_child_content("AssumeRoleResult|Credentials|AccessKeyId")
stringCompare:set_string(accessKey)
local stringMatch13 = stringCompare:contents_equal("", true)
if (not xml.last_method_success) or (stringMatch13) then
print("Missing or empty AssumeRoleResult|Credentials|AccessKeyId.")
return
end
local secretKey = xml:get_child_content("AssumeRoleResult|Credentials|SecretAccessKey")
stringCompare:set_string(secretKey)
local stringMatch14 = stringCompare:contents_equal("", true)
if (not xml.last_method_success) or (stringMatch14) then
print("Missing or empty AssumeRoleResult|Credentials|SecretAccessKey.")
return
end
local sessionToken = xml:get_child_content("AssumeRoleResult|Credentials|SessionToken")
stringCompare:set_string(sessionToken)
local stringMatch15 = stringCompare:contents_equal("", true)
if (not xml.last_method_success) or (stringMatch15) then
print("Missing or empty AssumeRoleResult|Credentials|SessionToken.")
return
end
local expiration = xml:get_child_content("AssumeRoleResult|Credentials|Expiration")
stringCompare:set_string(expiration)
local stringMatch16 = stringCompare:contents_equal("", true)
if (not xml.last_method_success) or (stringMatch16) then
print("Missing or empty AssumeRoleResult|Credentials|Expiration.")
return
end
success = expires:set_from_timestamp(expiration)
if not success then
print("Returned 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("Returned credentials are expired or expire within 60 seconds; obtain fresh credentials.")
return
end
value = xml:get_child_content("AssumeRoleResult|AssumedRoleUser|Arn")
stringCompare:set_string(value)
local stringMatch17 = stringCompare:contents_equal("", true)
if (not xml.last_method_success) or (stringMatch17) then
print("Missing or empty AssumeRoleResult|AssumedRoleUser|Arn.")
return
end
value = xml:get_child_content("AssumeRoleResult|AssumedRoleUser|AssumedRoleId")
stringCompare:set_string(value)
local stringMatch18 = stringCompare:contents_equal("", true)
if (not xml.last_method_success) or (stringMatch18) then
print("Missing or empty AssumeRoleResult|AssumedRoleUser|AssumedRoleId.")
return
end
-- Contains plaintext credentials. Pre-protect this directory/file with OS permissions.
-- Reuses the existing handoff filename for the companion S3 example.
success = xml:save_xml("qa_data/tokens/aws_session_token.xml")
if not success then
print("Could not save the private credential file; do not assume it was updated.")
return
end
print("Temporary credentials saved privately; expiration: " .. expiration)