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

S3: Download and Decompress a CloudTrail Log

See more S3 - HTTP Examples

Uses Chilkat.Http with Amazon S3 general purpose buckets and Signature Version 4. These examples do not cover directory buckets/S3 Express, access-point ARNs, Outposts, or other specialized endpoints. They target the commercial AWS partition; other partitions need their documented endpoint suffix.

Load private qa_data/aws/s3.json containing nonempty string fields access_key and secret_key, plus session_token for temporary credentials. Prefer short-lived role credentials. These samples do not discover AWS profiles or refresh credentials. Set the bucket's actual region and replace sample bucket names and object keys. TLS certificate verification is explicitly enabled. Keep detailed HTTP diagnostics private because they can contain credentials or presigned URLs.

Downloads the exact key to an unused temporary path, requires HTTP 200, compares the local byte count with Content-Length, and renames only after success. Create the output directory first. Interrupted or failed downloads are not promoted to the final path. This is not a resumable download and does not independently verify an S3 checksum; ETag must not be assumed to be MD5.

Requires s3:GetObject, or s3:GetObjectVersion for a specified version, plus applicable KMS permissions. Archived S3 Glacier Flexible Retrieval or Deep Archive objects must be restored before reading; a restoration request does not immediately make them downloadable. Use the original key without adding a leading slash.

The S3 bucket region can differ from the region named in the CloudTrail key. Use the bucket region for signing. This example decompresses one gzip log, requires valid JSON and a Records array, and reports only the event count. It does not validate CloudTrail digest signatures or establish log authenticity.

AWS reference

Chilkat Lua Downloads

Lua
local chilkat = require("chilkat")

local stringCompare = chilkat.StringBuilder.new()
-- This example requires the Chilkat API to have been previously unlocked.
-- See Global Unlock Sample for sample code.
-- Load private credentials; never put access keys or session tokens in source.
local credentials = chilkat.JsonObject.new()
credentials.strict = true
local success = credentials:load_file("qa_data/aws/s3.json")
if not success then
    print("Could not load private S3 credentials.")
    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 http = chilkat.Http.new()
http.aws_access_key = credentials:string_of("access_key")
http.aws_secret_key = credentials:string_of("secret_key")
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("session_token must be a nonempty string when supplied.")
        return
    end

    http.aws_session_token = credentials:string_of("session_token")
end

-- Current Chilkat uses SigV4 by default. Do not select deprecated SigV2.
-- Set the actual bucket region, not the caller's location.
local region = "us-west-2"
http.aws_region = region
local endpoint = chilkat.StringBuilder.new()
endpoint:append("s3.")
endpoint:append(region)
endpoint:append(".amazonaws.com")
http.aws_endpoint = endpoint:get_as_string()
http.require_ssl_cert_verify = true
http.follow_redirects = false
-- A region redirect is not success. Correct the endpoint and signing region.
local bucketName = "your-bucket-name"
-- A leading slash is part of a key. Do not add one to imitate a file path.
local objectName = "AWSLogs/123456789012/CloudTrail/us-west-2/2026/11/24/your-log.json.gz"

-- Start with the original key. Encode once and retain '/' path separators.
-- This also protects a literal "%2F" from being interpreted as a slash.
local keyPath = chilkat.StringBuilder.new()
keyPath:append(http:url_encode(objectName))
local slashCount = keyPath:replace_no_case("%2f", "/")
local encodedKey = keyPath:get_as_string()
local files = chilkat.FileAccess.new()
local finalPath = "qa_output/cloudtrail.json.gz"
local partialPath = "qa_output/cloudtrail.json.gz.part"
if (files:file_exists(finalPath)) or (files:file_exists(partialPath)) then
    print("Choose unused output paths before downloading.")
    return
end

success = http:s3_download_file(bucketName, encodedKey, partialPath)
if not success then
    print("Request failed (transport or S3 error). HTTP status: " .. http.last_status)
    -- Inspect LastErrorText privately. Do not log credentials or signed URLs.
    return
end

if http.last_status ~= 200 then
    print("Unexpected HTTP status: " .. http.last_status)
    return
end

local headers = chilkat.Mime.new()
success = headers:load_mime(http.last_response_header)
if not success then
    print("Could not parse download headers; keep the .part file.")
    return
end

local expectedSize = headers:get_header_field("Content-Length")
stringCompare:set_string(expectedSize)
local stringMatch4 = stringCompare:contents_equal("", true)
if (not headers.last_method_success) or (stringMatch4) then
    print("Missing Content-Length; keep the .part file.")
    return
end

local actualSize = files:file_size_str(partialPath)
stringCompare:set_string(actualSize)
local stringMatch5 = stringCompare:contents_equal(expectedSize, true)
if (not files.last_method_success) or (not stringMatch5) then
    print("Downloaded byte count mismatch; keep the .part file.")
    return
end

success = files:file_rename(partialPath, finalPath)
if not success then
    print("Downloaded file remains at the .part path; rename failed.")
    return
end

local jsonPath = "qa_output/cloudtrail.json"
local jsonPartial = "qa_output/cloudtrail.json.part"
if (files:file_exists(jsonPath)) or (files:file_exists(jsonPartial)) then
    print("Choose unused JSON output paths; compressed download is preserved.")
    return
end

local gzip = chilkat.Gzip.new()
success = gzip:uncompress_file(finalPath, jsonPartial)
if not success then
    print("Could not decompress the downloaded CloudTrail object.")
    return
end

local log = chilkat.JsonObject.new()
log.strict = true
success = log:load_file(jsonPartial)
if not success then
    print("Decompressed log is not valid JSON.")
    return
end

if log:json_type_of("Records") ~= 4 then
    print("CloudTrail log has no Records array.")
    return
end

success = files:file_rename(jsonPartial, jsonPath)
if not success then
    print("Validated log remains at its temporary path.")
    return
end

print("CloudTrail log downloaded and parsed. Records: " .. log:size_of_array("Records"))
-- Do not print full events to shared logs; they can contain sensitive activity.