README
¶
kcp Lambda scanner
A one-shot AWS Lambda that runs kcp scan steps from inside the cluster's VPC, so private MSK
clusters (brokers not reachable from outside) can be scanned. It bundles the kcp binary, runs it with the AWS credentials from the invoke
payload (e.g. short-lived STS credentials), and returns kcp-state.json in the response. It is a separate package main (custom runtime
bootstrap), not a kcp subcommand.
Build
make build-lambda-scanner VERSION=v1.2.3 # dist/kcp-lambda-scanner-linux-arm64.zip (bootstrap + kcp), prints SHA-256
VERSION sets the version reported by the bundled kcp (default 0.0.0-localdev).
Event
{
"cluster_arn": "arn:aws:kafka:us-east-1:123456789012:cluster/demo/abc",
"region": "us-east-1",
"steps": ["discover", "scan-clusters", "scan-msk-connectors", "scan-self-managed-connectors", "scan-schema-registry"],
"aws_access_key_id": "...", "aws_secret_access_key": "...", "aws_session_token": "...",
"state": {}, "credentials_yaml": "...",
"skip_metrics": false,
"connector_metrics_granularity": "1d",
"connect_rest_url": "http://connect:8083",
"connect_auth": {"type": "basic", "username": "...", "password": "..."},
"sasl_secret_arn": "arn:aws:secretsmanager:us-east-1:123456789012:secret:AmazonMSK_demo-AbCdEf",
"connect_insecure_skip_tls_verify": false,
"schema_registries": [
{"type": "confluent", "url": "https://sr:8081", "auth": {"type": "basic", "username": "...", "password": "..."}, "insecure_skip_tls_verify": false},
{"type": "glue", "registry_name": "my-registry", "region": "us-east-1"}
],
"auth_method": "sasl_scram",
"log_tail_bytes": 6000
}
- Inline passwords (
credentials_yamlSASL passwords,connect_auth.password, schema registryauth.password) are meant for callers that own the credentials; otherwise usesecret_arn. cluster_arn,region,aws_access_key_idandaws_secret_access_keyare required;regionmust match the region incluster_arn.stepsdefaults to all; steps always run in the order above. Unknown steps are rejected.- If
discoveris not a step, passstateandcredentials_yamlfrom an earlier discover. scan-self-managed-connectorsonly runs whenconnect_rest_urlis set. The Connect password is passed to kcp through its environment, never on the command line.scan-schema-registryruns last, once perschema_registriesitem (needs state).confluentneedsurland optionalauth(unauthenticateddefault, orbasic; the password goes to kcp via its environment, never argv);glueneedsregistry_nameand usesregion(default: event region) with the payload AWS credentials. mTLS and custom CA (use_mtls,tls_ca_cert) are rejected: not supported yet (same file-path limitation as Kafka TLS). If requested with an empty list it is reported as skipped; each result carries atargetnaming the registry.sasl_secret_arn,connect_auth.secret_arnandschema_registries[].auth.secret_arntake a Secrets Manager ARN instead of a password; see Credentials from Secrets Manager.secret_arnandpasswordare mutually exclusive, andsecret_arnrequirestype: basic.- Validation:
credentials_yamlmust be valid YAML (otherwise rejected with a generic error that does not quote the input), andconnect_rest_urlandschema_registries[].urlmust not contain userinfo (https://user:pass@host); use the auth fields instead. - If
discoverfails and nostatewas supplied, the remaining steps are skipped. log_tail_bytesis capped at 64 KiB.connector_metrics_granularity:60s,5m,1hor1d(default1d);noneskips metrics. Other values are rejected before any step runs.state_gzip_b64is accepted as an input too (gzip + base64 of the state JSON), mutually exclusive withstate. Pass back whichever form the previous response carried. The whole request payload must fit Lambda's 6 MB synchronous limit, so usestate_gzip_b64for large state.auth_method(validated;iam,sasl_scram,sasl_plain,tls,unauthenticated_tls,unauthenticated_plaintext) rewritesuse:inmsk-credentials.yamlso only that method is used byscan-clusters. Without it kcp may pick unauthenticated plaintext and return no ACLs. If the rewrite fails, the step fails instead of falling back to the discovered auth. The override applies only to the copy of the credentials handed to kcp; the returnedcredentials_yamlis left as discovered or supplied.
Response
steps[] (step, args with passwords redacted, exit_code (-1 = skipped), duration_ms,
log_tail, warnings = WARN/ERROR lines from kcp.log), duration_ms, error, state_bytes,
and the state as either state (raw JSON, up to 3 MiB) or state_gzip_b64 (gzip + base64).
credentials_yaml is returned when discover ran, with usernames, passwords and client keys
blanked (keep your own copy of any secrets you supplied); TLS client_key (like ca_cert and
client_cert) is a file path, and is blanked anyway. Known secret values are also masked in
logs and args. Responses over about 5.5 MB are replaced by an error result without state or logs.
Invalid events (bad JSON, validation errors) are reported as a Lambda function error.
IAM
- Execution role: only
AWSLambdaENIManagementAccess(VPC ENI management). It has no data access; the scan uses the caller's credentials from the payload, and the function role's credentials are never passed to kcp. The only use of the role's own credentials is reading Secrets Manager secrets named bysecret_arnfields (see above). - Caller credentials in the payload: the same permissions as the kcp
discover/scancommands being run.
Credentials from Secrets Manager
Pass a secret ARN instead of a password so the caller never handles the secret value. Each secret
is JSON in the MSK SCRAM format, {"username": "...", "password": "..."}, and both keys are required.
sasl_secret_arn: applied to thecluster_arnentry inmsk-credentials.yamlbeforescan-clusters: it sets the username and password onsasl_scram(or onsasl_plainwhenauth_methodissasl_plain). Ifauth_methodis empty it is set tosasl_scram. If the read fails, thescan-clustersstep fails (the invoke continues with the other steps).connect_auth.secret_arnandschema_registries[].auth.secret_arn(typebasic): replace the username and password.
The Lambda reads each distinct ARN once per invoke, in parallel, with its own execution role
credentials, in the region of the ARN (one client per region). All reads share a single 30 s
timeout. Those credentials are never passed to kcp. Secret-sourced usernames and passwords are
passed to kcp through its environment (USERNAME, PASSWORD), never on the command line, and are
added to the log scrubber before any step runs; secret values (username and password) are never
returned or logged. For sasl_secret_arn they are written only to the filtered credentials copy
that kcp reads. Inline usernames are passed with --username and appear in args.
Errors may include the ARN and the AWS error code and message. Inline passwords remain supported,
but secret_arn is recommended.
Permissions
If the execution role's own policies and permission boundary allow secretsmanager:GetSecretValue on the secret and kms:Decrypt through Secrets Manager (kms:ViaService), no resource-policy grant is needed; the statements below are for roles whose boundary does not allow this, such as AWSLambdaENIManagementAccess.
For such roles identity-based grants do not work. Access comes from the secret's resource policy, plus (for customer-managed KMS
keys, which MSK SCRAM secrets require) a kms:Decrypt statement in the key policy. Append these to
the existing policies: MSK secrets already have a kafka.amazonaws.com statement, and
put-resource-policy replaces the whole policy.
Recommended: Principal: "*" restricted to one fixed role ARN with ArnEquals (no wildcard), so
use the same scanner role name on every run. aws:PrincipalArn grants are not limited by the
permission boundary, survive the role being deleted and recreated with the same name, and fixed
values keep the policy non-public for Secrets Manager's public-policy check and for key-policy
public-access checks (wildcards in the condition can be reported as public).
Secret resource policy statement:
{
"Sid": "AllowScannerRead",
"Effect": "Allow",
"Principal": "*",
"Action": "secretsmanager:GetSecretValue",
"Resource": "*",
"Condition": {
"ArnEquals": {"aws:PrincipalArn": "arn:aws:iam::123456789012:role/<scanner-role>"},
"StringEquals": {"aws:PrincipalAccount": "123456789012"}
}
}
KMS key policy statement:
{
"Sid": "AllowScannerDecryptViaSecretsManager",
"Effect": "Allow",
"Principal": "*",
"Action": "kms:Decrypt",
"Resource": "*",
"Condition": {
"ArnEquals": {"aws:PrincipalArn": "arn:aws:iam::123456789012:role/<scanner-role>"},
"StringEquals": {
"kms:CallerAccount": "123456789012",
"kms:ViaService": "secretsmanager.us-east-1.amazonaws.com",
"kms:EncryptionContext:SecretARN": "arn:aws:secretsmanager:us-east-1:123456789012:secret:<secret-name>"
}
}
}
Notes:
- Anyone in the account allowed to create a role with that name can use the grant, so restrict
iam:CreateRoleon it, and remove the statements when scans are no longer needed. If the VPC has a Secrets Manager interface endpoint, anaws:SourceVpcecondition narrows it further. - Alternative:
Principal: {"AWS": "arn:aws:sts::123456789012:assumed-role/<scanner-role>/<function-name>"}(Lambda's session name is the function name), which needs fixed role and function names. AWS prefers role principals over session principals, and KMS requires key-policy principals to exist when the policy is set. - These do not work, because the permission boundary applies: the role ARN as
Principal, or the account root asPrincipalwith anaws:PrincipalArncondition.
Deploy, invoke, clean up
aws lambda create-function --function-name kcp-scanner --runtime provided.al2023 \
--architectures arm64 --handler bootstrap --timeout 900 --memory-size 1024 \
--role arn:aws:iam::123456789012:role/kcp-scanner-exec \
--zip-file fileb://dist/kcp-lambda-scanner-linux-arm64.zip \
--vpc-config SubnetIds=subnet-aaa,subnet-bbb,SecurityGroupIds=sg-ccc
# While the function is Pending, invoke returns ResourceConflictException: retry until Active.
aws lambda wait function-active-v2 --function-name kcp-scanner
aws lambda invoke --function-name kcp-scanner --cli-binary-format raw-in-base64-out \
--cli-read-timeout 960 --payload fileb://event.json out.json
# --cli-read-timeout must exceed the 900 s function timeout; the CLI default (60 s) would drop
# the connection on a long scan while the function keeps running.
aws lambda delete-function --function-name kcp-scanner
Use the cluster's own subnets and security group. Lambda VPC ENIs are released about 20 minutes after the function is deleted.
Limits
- 15 minute maximum run time; 6 MB response limit (large state is gzipped).
- Confluent schema registries must be reachable from the cluster subnets/security group.
- Brokers must be reachable from the chosen subnets/security group.
discover,scan-msk-connectorsand Gluescan-schema-registrycall AWS APIs from inside the Lambda, so the VPC needs NAT or VPC endpoints.- Supported auth: IAM, SASL/SCRAM, SASL/PLAIN (secrets in
credentials_yaml) and unauthenticated. TLS client-cert (mTLS) and custom-CA TLS are not supported yet, becauseca_cert,client_certandclient_keyin the credentials file are file paths that the payload cannot supply (follow-up: afilesmap written under the working directory). - MSK Serverless: ACLs are not available via the Kafka Admin API, so kcp skips them with a WARN.
- The scan stops about 30 seconds before the Lambda deadline and returns the state from the steps that
completed, with an error note. kcp is killed at that point and writes state only at the end of a
step, so the interrupted step's results are lost. Stale
/tmp/kcp-*dirs from a killed sandbox are removed on start.
Security
- The event payload (credentials) is never logged; only per-step exit codes and durations are.
- kcp runs with only the payload credentials (
AWS_EC2_METADATA_DISABLED=true); all files live under/tmpand are removed after each invocation. - Verify the deployed code: compare the zip's SHA-256 (printed by
make build-lambda-scanner) with the function'sCodeSha256:aws lambda get-function-configuration --function-name kcp-scanner --query CodeSha256 --output text(Lambda reports base64;openssl dgst -sha256 -binary <zip> | base64).
Design and follow-ups
The handler exec's the bundled kcp CLI (proven path). A future version may call the kcp packages
directly. Releasing the zip is a follow-up: add a goreleaser builds entry for cmd/lambda-scanner
(linux/arm64) plus an archive step that zips it with the kcp binary, and attach it to the release.
Documentation
¶
Overview ¶
Command lambda-scanner is a one-shot AWS Lambda (custom runtime, provided.al2023) that runs kcp scan steps from inside the cluster's VPC, so private MSK clusters can be scanned, and returns the resulting kcp-state.json in the invoke response.
Design: the handler exec's the bundled kcp CLI (found in $LAMBDA_TASK_ROOT) for each step with only the credentials from the event payload in its environment; the function role's own credentials are dropped. This keeps the Lambda a thin wrapper over the exact code path users run locally. A future version may call the kcp packages directly instead of exec'ing the CLI.
This is not a Cobra subcommand and must not be imported by the main kcp binary.