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

AWS Secrets Manager: Read, Validate, and Apply a Resource Policy

See more AWS Secrets Manager Examples

Reads the current resource policy, validates a replacement from qa_data/aws/secret-policy.json, and optionally applies it with BlockPublicPolicy=true. The default only validates. Prepare a policy limited to the intended principal ARN, actions, resource and conditions; inspect existing statements before replacing the complete policy. No wildcard-principal example is supplied.

Validation checks syntax, broad access and caller lockout. HTTP 200 alone is insufficient: PolicyValidationPassed must be true. PutResourcePolicy replaces rather than merges the policy; coordinate concurrent policy edits because there is no revision precondition here. BlockPublicPolicy also checks at the write step but is not a complete permissions audit.

Cross-account access also needs caller-side IAM permissions and a customer-managed KMS key/policy allowing decryption. This example does not grant KMS or IAM permissions. Account policies, explicit denies and other controls still apply.

Required actions: secretsmanager:GetResourcePolicy, secretsmanager:ValidateResourcePolicy, secretsmanager:PutResourcePolicy.

Uses direct Chilkat.Rest requests with AWS Signature Version 4, signing service secretsmanager, and the AWS JSON 1.1 protocol. Configure the region in the code. The illustrated amazonaws.com endpoint is for the commercial AWS partition; use the appropriate endpoint for other partitions. HTTPS certificate verification is enabled.

Supply nonempty string fields access_key and secret_key in private qa_data/aws/secrets-manager.json. For temporary role or STS credentials, also supply the matching nonempty session_token; it is included in the signed query. Prefer short-lived role credentials in production. These samples consume credentials already obtained by the application; they do not implement an SDK credential-provider chain or refresh expired credentials. Protect local credential files and keep them outside source control and public web directories.

The sample distinguishes transport failures, HTTP errors, and invalid JSON. It prints status, AWS error code, and request ID, without printing secret values or full diagnostic bodies. Request URLs and Chilkat diagnostics can contain sensitive data; inspect them privately. Production retry policies should use bounded exponential backoff with jitter for transient failures. Reconcile uncertain writes and preserve their idempotency token and payload before retrying.

AWS ValidateResourcePolicy reference

Chilkat Lua Downloads

Lua
local chilkat = require("chilkat")

local stringCompare = chilkat.StringBuilder.new()
-- Assumes Chilkat is unlocked. See Global Unlock Sample.
-- Keep this credentials file outside public web content and source control.
local credentials = chilkat.JsonObject.new()
credentials.strict = true
local success = credentials:load_file("qa_data/aws/secrets-manager.json")
if not success then
    print("Could not load private Secrets Manager 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 region = "us-west-2"
local endpoint = chilkat.StringBuilder.new()
endpoint:append("secretsmanager.")
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 = "secretsmanager"
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 AWS signing.")
    return
end

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
end

local connection = chilkat.Socket.new()
connection.require_ssl_cert_verify = true
connection.max_read_idle_ms = 60000
connection.max_send_idle_ms = 60000
-- Keep connection alive while Rest uses it.
local body = chilkat.JsonObject.new()
local result = chilkat.JsonObject.new()
result.strict = true
-- Use a secret name or complete ARN. IDs remain opaque strings.
local secretId = "example/application"
-- Validation-only by default. Set true after reviewing the replacement policy.
local applyPolicy = false
local proposed = chilkat.JsonObject.new()
proposed.strict = true
success = proposed:load_file("qa_data/aws/secret-policy.json")
if not success then
    print("Could not load the proposed policy JSON.")
    return
end

if (proposed:json_type_of("Statement") ~= 3) and (proposed:json_type_of("Statement") ~= 4) then
    print("Expected a policy Statement object or array.")
    return
end

success = body:update_string("SecretId", secretId)
if not success then
    print("Could not set SecretId.")
    return
end

success = rest:clear_all_query_params()
if not success then
    print("Could not clear query parameters.")
    return
end

-- Temporary role credentials require the session token as well as both keys.
-- Include it in the signed query; keep request URLs and diagnostics private.
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 session token.")
        return
    end
end

success = rest:add_header("Content-Type", "application/x-amz-json-1.1")
if not success then
    print("Could not set content type.")
    return
end

success = rest:add_header("X-Amz-Target", "secretsmanager.GetResourcePolicy")
if not success then
    print("Could not select operation.")
    return
end

-- Establish a connection for this deliberate operation. Do not replay a write
-- automatically if the server receives it but its response is lost.
rest:disconnect(10)
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, false)
if not success then
    print("Could not attach the TLS connection.")
    return
end

local responseJson = rest:full_request_string("POST", "/", body:emit())
if not rest.last_method_success then
    print("Secrets Manager request did not complete; inspect diagnostics privately. A write may have succeeded.")
    return
end

if rest.response_status_code ~= 200 then
    print("Secrets Manager HTTP status: " .. rest.response_status_code)
    success = result:load(responseJson)
    if success then
        if result:json_type_of("__type") == 1 then
            print("AWS error code: " .. result:string_of("__type"))
        end
    end

    print("AWS request ID: " .. rest:response_hdr_by_name("x-amzn-RequestId"))
    -- Do not print response bodies, request bodies, credentials, or secret values.
    return
end

success = result:load(responseJson)
if not success then
    print("Expected a well-formed JSON response.")
    return
end

stringCompare:set_string(result:string_of("ARN"))
local stringMatch4 = stringCompare:contents_equal("", true)
if (result:json_type_of("ARN") ~= 1) or (stringMatch4) then
    print("Missing or invalid ARN.")
    return
end

secretId = result:string_of("ARN")
local previousPolicy = ""
if result:has_member("ResourcePolicy") then
    if result:json_type_of("ResourcePolicy") ~= 1 then
        print("Missing or invalid ResourcePolicy.")
        return
    end

    previousPolicy = result:string_of("ResourcePolicy")
    -- Review/save the existing policy privately before replacing it.
end

body:clear()
success = body:update_string("SecretId", secretId)
if not success then
    print("Could not set SecretId.")
    return
end

success = body:update_string("ResourcePolicy", proposed:emit())
if not success then
    print("Could not set ResourcePolicy.")
    return
end

success = rest:clear_all_query_params()
if not success then
    print("Could not clear query parameters.")
    return
end

-- Temporary role credentials require the session token as well as both keys.
-- Include it in the signed query; keep request URLs and diagnostics private.
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 session token.")
        return
    end
end

success = rest:add_header("Content-Type", "application/x-amz-json-1.1")
if not success then
    print("Could not set content type.")
    return
end

success = rest:add_header("X-Amz-Target", "secretsmanager.ValidateResourcePolicy")
if not success then
    print("Could not select operation.")
    return
end

-- Establish a connection for this deliberate operation. Do not replay a write
-- automatically if the server receives it but its response is lost.
rest:disconnect(10)
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, false)
if not success then
    print("Could not attach the TLS connection.")
    return
end

responseJson = rest:full_request_string("POST", "/", body:emit())
if not rest.last_method_success then
    print("Secrets Manager request did not complete; inspect diagnostics privately. A write may have succeeded.")
    return
end

if rest.response_status_code ~= 200 then
    print("Secrets Manager HTTP status: " .. rest.response_status_code)
    success = result:load(responseJson)
    if success then
        if result:json_type_of("__type") == 1 then
            print("AWS error code: " .. result:string_of("__type"))
        end
    end

    print("AWS request ID: " .. rest:response_hdr_by_name("x-amzn-RequestId"))
    -- Do not print response bodies, request bodies, credentials, or secret values.
    return
end

success = result:load(responseJson)
if not success then
    print("Expected a well-formed JSON response.")
    return
end

if result:json_type_of("PolicyValidationPassed") ~= 5 then
    print("Missing or invalid PolicyValidationPassed.")
    return
end

if not result:bool_of("PolicyValidationPassed") then
    print("Policy validation failed; no policy was applied. Inspect ValidationErrors privately.")
    return
end

if not applyPolicy then
    print("Policy validation passed. Review the existing/replacement policies before enabling applyPolicy.")
    return
end

body:clear()
success = body:update_string("SecretId", secretId)
if not success then
    print("Could not set SecretId.")
    return
end

success = body:update_string("ResourcePolicy", proposed:emit())
if not success then
    print("Could not set ResourcePolicy.")
    return
end

success = body:update_bool("BlockPublicPolicy", true)
if not success then
    print("Could not set BlockPublicPolicy.")
    return
end

success = rest:clear_all_query_params()
if not success then
    print("Could not clear query parameters.")
    return
end

-- Temporary role credentials require the session token as well as both keys.
-- Include it in the signed query; keep request URLs and diagnostics private.
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 session token.")
        return
    end
end

success = rest:add_header("Content-Type", "application/x-amz-json-1.1")
if not success then
    print("Could not set content type.")
    return
end

success = rest:add_header("X-Amz-Target", "secretsmanager.PutResourcePolicy")
if not success then
    print("Could not select operation.")
    return
end

-- Establish a connection for this deliberate operation. Do not replay a write
-- automatically if the server receives it but its response is lost.
rest:disconnect(10)
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, false)
if not success then
    print("Could not attach the TLS connection.")
    return
end

responseJson = rest:full_request_string("POST", "/", body:emit())
if not rest.last_method_success then
    print("Secrets Manager request did not complete; inspect diagnostics privately. A write may have succeeded.")
    return
end

if rest.response_status_code ~= 200 then
    print("Secrets Manager HTTP status: " .. rest.response_status_code)
    success = result:load(responseJson)
    if success then
        if result:json_type_of("__type") == 1 then
            print("AWS error code: " .. result:string_of("__type"))
        end
    end

    print("AWS request ID: " .. rest:response_hdr_by_name("x-amzn-RequestId"))
    -- Do not print response bodies, request bodies, credentials, or secret values.
    return
end

success = result:load(responseJson)
if not success then
    print("Expected a well-formed JSON response.")
    return
end

stringCompare:set_string(result:string_of("ARN"))
local stringMatch5 = stringCompare:contents_equal("", true)
if (result:json_type_of("ARN") ~= 1) or (stringMatch5) then
    print("Missing or invalid ARN.")
    return
end

print("Restricted resource policy applied to: " .. result:string_of("ARN"))
-- PutResourcePolicy replaces the attached policy; it does not merge statements.