# This policy requires AWS Step Functions state machines to have logging configuration enabled with level set to "ALL", "ERROR", or "FATAL".

# Copyright IBM Corp. 2025, 2026
# SPDX-License-Identifier: BUSL-1.1

# Imports
import "tfplan/v2" as tfplan
import "tfresources" as tf
import "report" as report
import "collection" as collection
import "collection/maps" as maps

# Constants
const = {
	"policy_name":         "sfn-logging-enabled",
	"message":             "AWS Step Functions state machines must have logging enabled with level set to 'ALL', 'ERROR', or 'FATAL'. Refer to https://docs.aws.amazon.com/securityhub/latest/userguide/stepfunctions-controls.html#stepfunctions-1 for more details.",
	"resource_aws_sfn":    "aws_sfn_state_machine",
	"logging_config":      "logging_configuration",
	"required_log_levels": ["ALL", "ERROR", "FATAL"],
}

# Variables
resources = tf.plan(tfplan.planned_values.resources).type(const.resource_aws_sfn).resources

violations = collection.reject(resources, func(res) {
	logging_config = maps.get(res, "values." + const.logging_config, null)

	if logging_config is null {
		return false
	}
	log_level = maps.get(logging_config[0], "level", null)
	if log_level is null {
		return false
	}

	return log_level in const.required_log_levels
})

summary = {
	"policy_name": const.policy_name,
	"violations": map violations as _, v {
		{
			"address":        v.address,
			"module_address": v.module_address,
			"message":        const.message,
		}
	},
}

# Outputs
print(report.generate_policy_report(summary))

# Rules
main = rule {
	violations is empty
}
