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 Delphi DLL Downloads
var
success: Boolean;
stringCompare: HCkStringBuilder;
credentials: HCkJsonObject;
stringMatch1: Boolean;
stringMatch2: Boolean;
http: HCkHttp;
stringMatch3: Boolean;
region: PWideChar;
endpoint: HCkStringBuilder;
bucketName: PWideChar;
objectName: PWideChar;
keyPath: HCkStringBuilder;
slashCount: Integer;
encodedKey: PWideChar;
files: HCkFileAccess;
finalPath: PWideChar;
partialPath: PWideChar;
headers: HCkMime;
expectedSize: PWideChar;
stringMatch4: Boolean;
actualSize: PWideChar;
stringMatch5: Boolean;
jsonPath: PWideChar;
jsonPartial: PWideChar;
gzip: HCkGzip;
log: HCkJsonObject;
begin
success := False;
stringCompare := CkStringBuilder_Create();
// 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.
credentials := CkJsonObject_Create();
CkJsonObject_putStrict(credentials,True);
success := CkJsonObject_LoadFile(credentials,'qa_data/aws/s3.json');
if (success <> True) then
begin
Memo1.Lines.Add('Could not load private S3 credentials.');
Exit;
end;
CkStringBuilder_SetString(stringCompare,CkJsonObject__stringOf(credentials,'access_key'));
stringMatch1 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
if ((CkJsonObject_JsonTypeOf(credentials,'access_key') <> 1) or (stringMatch1 = True)) then
begin
Memo1.Lines.Add('Missing or invalid access_key.');
Exit;
end;
CkStringBuilder_SetString(stringCompare,CkJsonObject__stringOf(credentials,'secret_key'));
stringMatch2 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
if ((CkJsonObject_JsonTypeOf(credentials,'secret_key') <> 1) or (stringMatch2 = True)) then
begin
Memo1.Lines.Add('Missing or invalid secret_key.');
Exit;
end;
http := CkHttp_Create();
CkHttp_putAwsAccessKey(http,CkJsonObject__stringOf(credentials,'access_key'));
CkHttp_putAwsSecretKey(http,CkJsonObject__stringOf(credentials,'secret_key'));
if (CkJsonObject_HasMember(credentials,'session_token') = True) then
begin
CkStringBuilder_SetString(stringCompare,CkJsonObject__stringOf(credentials,'session_token'));
stringMatch3 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
if ((CkJsonObject_JsonTypeOf(credentials,'session_token') <> 1) or (stringMatch3 = True)) then
begin
Memo1.Lines.Add('session_token must be a nonempty string when supplied.');
Exit;
end;
CkHttp_putAwsSessionToken(http,CkJsonObject__stringOf(credentials,'session_token'));
end;
// Current Chilkat uses SigV4 by default. Do not select deprecated SigV2.
// Set the actual bucket region, not the caller's location.
region := 'us-west-2';
CkHttp_putAwsRegion(http,region);
endpoint := CkStringBuilder_Create();
CkStringBuilder_Append(endpoint,'s3.');
CkStringBuilder_Append(endpoint,region);
CkStringBuilder_Append(endpoint,'.amazonaws.com');
CkHttp_putAwsEndpoint(http,CkStringBuilder__getAsString(endpoint));
CkHttp_putRequireSslCertVerify(http,True);
CkHttp_putFollowRedirects(http,False);
// A region redirect is not success. Correct the endpoint and signing region.
bucketName := 'your-bucket-name';
// A leading slash is part of a key. Do not add one to imitate a file path.
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.
keyPath := CkStringBuilder_Create();
CkStringBuilder_Append(keyPath,CkHttp__urlEncode(http,objectName));
slashCount := CkStringBuilder_ReplaceNoCase(keyPath,'%2f','/');
encodedKey := CkStringBuilder__getAsString(keyPath);
files := CkFileAccess_Create();
finalPath := 'qa_output/cloudtrail.json.gz';
partialPath := 'qa_output/cloudtrail.json.gz.part';
if ((CkFileAccess_FileExists(files,finalPath) = True) or (CkFileAccess_FileExists(files,partialPath) = True)) then
begin
Memo1.Lines.Add('Choose unused output paths before downloading.');
Exit;
end;
success := CkHttp_S3_DownloadFile(http,bucketName,encodedKey,partialPath);
if (success <> True) then
begin
Memo1.Lines.Add('Request failed (transport or S3 error). HTTP status: ' + IntToStr(CkHttp_getLastStatus(http)));
// Inspect LastErrorText privately. Do not log credentials or signed URLs.
Exit;
end;
if (CkHttp_getLastStatus(http) <> 200) then
begin
Memo1.Lines.Add('Unexpected HTTP status: ' + IntToStr(CkHttp_getLastStatus(http)));
Exit;
end;
headers := CkMime_Create();
success := CkMime_LoadMime(headers,CkHttp__lastResponseHeader(http));
if (success <> True) then
begin
Memo1.Lines.Add('Could not parse download headers; keep the .part file.');
Exit;
end;
expectedSize := CkMime__getHeaderField(headers,'Content-Length');
CkStringBuilder_SetString(stringCompare,expectedSize);
stringMatch4 := CkStringBuilder_ContentsEqual(stringCompare,'',True);
if ((CkMime_getLastMethodSuccess(headers) <> True) or (stringMatch4 = True)) then
begin
Memo1.Lines.Add('Missing Content-Length; keep the .part file.');
Exit;
end;
actualSize := CkFileAccess__fileSizeStr(files,partialPath);
CkStringBuilder_SetString(stringCompare,actualSize);
stringMatch5 := CkStringBuilder_ContentsEqual(stringCompare,expectedSize,True);
if ((CkFileAccess_getLastMethodSuccess(files) <> True) or (stringMatch5 <> True)) then
begin
Memo1.Lines.Add('Downloaded byte count mismatch; keep the .part file.');
Exit;
end;
success := CkFileAccess_FileRename(files,partialPath,finalPath);
if (success <> True) then
begin
Memo1.Lines.Add('Downloaded file remains at the .part path; rename failed.');
Exit;
end;
jsonPath := 'qa_output/cloudtrail.json';
jsonPartial := 'qa_output/cloudtrail.json.part';
if ((CkFileAccess_FileExists(files,jsonPath) = True) or (CkFileAccess_FileExists(files,jsonPartial) = True)) then
begin
Memo1.Lines.Add('Choose unused JSON output paths; compressed download is preserved.');
Exit;
end;
gzip := CkGzip_Create();
success := CkGzip_UncompressFile(gzip,finalPath,jsonPartial);
if (success <> True) then
begin
Memo1.Lines.Add('Could not decompress the downloaded CloudTrail object.');
Exit;
end;
log := CkJsonObject_Create();
CkJsonObject_putStrict(log,True);
success := CkJsonObject_LoadFile(log,jsonPartial);
if (success <> True) then
begin
Memo1.Lines.Add('Decompressed log is not valid JSON.');
Exit;
end;
if (CkJsonObject_JsonTypeOf(log,'Records') <> 4) then
begin
Memo1.Lines.Add('CloudTrail log has no Records array.');
Exit;
end;
success := CkFileAccess_FileRename(files,jsonPartial,jsonPath);
if (success <> True) then
begin
Memo1.Lines.Add('Validated log remains at its temporary path.');
Exit;
end;
Memo1.Lines.Add('CloudTrail log downloaded and parsed. Records: ' + IntToStr(CkJsonObject_SizeOfArray(log,'Records')));
// Do not print full events to shared logs; they can contain sensitive activity.
CkStringBuilder_Dispose(stringCompare);
CkJsonObject_Dispose(credentials);
CkHttp_Dispose(http);
CkStringBuilder_Dispose(endpoint);
CkStringBuilder_Dispose(keyPath);
CkFileAccess_Dispose(files);
CkMime_Dispose(headers);
CkGzip_Dispose(gzip);
CkJsonObject_Dispose(log);