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.
Chilkat C# Downloads
bool success = false;
Chilkat.StringBuilder stringCompare = new Chilkat.StringBuilder();
// 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.
Chilkat.JsonObject credentials = new Chilkat.JsonObject();
credentials.Strict = true;
success = credentials.LoadFile("qa_data/aws/s3.json");
if (success != true) {
Debug.WriteLine("Could not load private S3 credentials.");
return;
}
stringCompare.SetString(credentials.StringOf("access_key"));
bool stringMatch1 = stringCompare.ContentsEqual("",true);
if ((credentials.JsonTypeOf("access_key") != 1) || (stringMatch1 == true)) {
Debug.WriteLine("Missing or invalid access_key.");
return;
}
stringCompare.SetString(credentials.StringOf("secret_key"));
bool stringMatch2 = stringCompare.ContentsEqual("",true);
if ((credentials.JsonTypeOf("secret_key") != 1) || (stringMatch2 == true)) {
Debug.WriteLine("Missing or invalid secret_key.");
return;
}
Chilkat.Http http = new Chilkat.Http();
http.AwsAccessKey = credentials.StringOf("access_key");
http.AwsSecretKey = credentials.StringOf("secret_key");
if (credentials.HasMember("session_token") == true) {
stringCompare.SetString(credentials.StringOf("session_token"));
bool stringMatch3 = stringCompare.ContentsEqual("",true);
if ((credentials.JsonTypeOf("session_token") != 1) || (stringMatch3 == true)) {
Debug.WriteLine("session_token must be a nonempty string when supplied.");
return;
}
http.AwsSessionToken = credentials.StringOf("session_token");
}
// Current Chilkat uses SigV4 by default. Do not select deprecated SigV2.
// Set the actual bucket region, not the caller's location.
string region = "us-west-2";
http.AwsRegion = region;
Chilkat.StringBuilder endpoint = new Chilkat.StringBuilder();
endpoint.Append("s3.");
endpoint.Append(region);
endpoint.Append(".amazonaws.com");
http.AwsEndpoint = endpoint.GetAsString();
http.RequireSslCertVerify = true;
http.FollowRedirects = false;
// A region redirect is not success. Correct the endpoint and signing region.
string bucketName = "your-bucket-name";
// A leading slash is part of a key. Do not add one to imitate a file path.
string 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.
Chilkat.StringBuilder keyPath = new Chilkat.StringBuilder();
keyPath.Append(http.UrlEncode(objectName));
int slashCount = keyPath.ReplaceNoCase("%2f","/");
string encodedKey = keyPath.GetAsString();
Chilkat.FileAccess files = new Chilkat.FileAccess();
string finalPath = "qa_output/cloudtrail.json.gz";
string partialPath = "qa_output/cloudtrail.json.gz.part";
if ((files.FileExists(finalPath) == true) || (files.FileExists(partialPath) == true)) {
Debug.WriteLine("Choose unused output paths before downloading.");
return;
}
success = http.S3_DownloadFile(bucketName,encodedKey,partialPath);
if (success != true) {
Debug.WriteLine("Request failed (transport or S3 error). HTTP status: " + Convert.ToString(http.LastStatus));
// Inspect LastErrorText privately. Do not log credentials or signed URLs.
return;
}
if (http.LastStatus != 200) {
Debug.WriteLine("Unexpected HTTP status: " + Convert.ToString(http.LastStatus));
return;
}
Chilkat.Mime headers = new Chilkat.Mime();
success = headers.LoadMime(http.LastResponseHeader);
if (success != true) {
Debug.WriteLine("Could not parse download headers; keep the .part file.");
return;
}
string expectedSize = headers.GetHeaderField("Content-Length");
stringCompare.SetString(expectedSize);
bool stringMatch4 = stringCompare.ContentsEqual("",true);
if ((headers.LastMethodSuccess != true) || (stringMatch4 == true)) {
Debug.WriteLine("Missing Content-Length; keep the .part file.");
return;
}
string actualSize = files.FileSizeStr(partialPath);
stringCompare.SetString(actualSize);
bool stringMatch5 = stringCompare.ContentsEqual(expectedSize,true);
if ((files.LastMethodSuccess != true) || (stringMatch5 != true)) {
Debug.WriteLine("Downloaded byte count mismatch; keep the .part file.");
return;
}
success = files.FileRename(partialPath,finalPath);
if (success != true) {
Debug.WriteLine("Downloaded file remains at the .part path; rename failed.");
return;
}
string jsonPath = "qa_output/cloudtrail.json";
string jsonPartial = "qa_output/cloudtrail.json.part";
if ((files.FileExists(jsonPath) == true) || (files.FileExists(jsonPartial) == true)) {
Debug.WriteLine("Choose unused JSON output paths; compressed download is preserved.");
return;
}
Chilkat.Gzip gzip = new Chilkat.Gzip();
success = gzip.UncompressFile(finalPath,jsonPartial);
if (success != true) {
Debug.WriteLine("Could not decompress the downloaded CloudTrail object.");
return;
}
Chilkat.JsonObject log = new Chilkat.JsonObject();
log.Strict = true;
success = log.LoadFile(jsonPartial);
if (success != true) {
Debug.WriteLine("Decompressed log is not valid JSON.");
return;
}
if (log.JsonTypeOf("Records") != 4) {
Debug.WriteLine("CloudTrail log has no Records array.");
return;
}
success = files.FileRename(jsonPartial,jsonPath);
if (success != true) {
Debug.WriteLine("Validated log remains at its temporary path.");
return;
}
Debug.WriteLine("CloudTrail log downloaded and parsed. Records: " + Convert.ToString(log.SizeOfArray("Records")));
// Do not print full events to shared logs; they can contain sensitive activity.