stelligent / cfn_nag

Linting tool for CloudFormation templates
MIT License
1.25k stars 209 forks source link

W58 requires excessive `logs:CreateLogGroup` permission #603

Open Veetaha opened 2 years ago

Veetaha commented 2 years ago

We create log groups for lambda functions as separate resources to be able to configure their logs retention period. To prohibit the lambda principal from creating the log group on its own we disallow the logs:CreateLogGroup for it:

/**
 * Creates a lambda function with execution role and an appropriate log group.
 */
export function createLambdaFunction(
    scope: cdk.Construct, id: string, props: lambda.FunctionProps, executionRoleStatements: iam.PolicyStatementProps[] = [],
): LambdaFunction {
    const role = new iam.Role(scope, `${id}LambdaExecutionRole`, {
        assumedBy: new iam.ServicePrincipal('lambda.amazonaws.com'),
    });

    role.addToPolicy(new iam.PolicyStatement({
        effect: iam.Effect.ALLOW,
        actions: [
            // logs:CreateLogGroup is not allowed, because we create the log group on our own via the CFN stack
            "logs:CreateLogStream",
            "logs:PutLogEvents",
        ],
        resources: [
            `arn:aws:logs:*:*:log-group:/aws/*/elastio-*:*`,
            `arn:aws:logs:*:*:log-group:/ecs/elastio-scalez-*:*`,
        ],
    }));
    executionRoleStatements.forEach(st => role.addToPolicy(new iam.PolicyStatement(st)));

    const createdLambda = new lambda.Function(scope, id, {
        ...props,
        role,
    });

    return {
        base: createdLambda,
        logGroup: new logs.LogGroup(
            scope,
            `${id}LogGroup`,
            {
                logGroupName: `/aws/lambda/${createdLambda.functionName}`,
                retention: logs.RetentionDays.ONE_WEEK,
            }
        )
    };
}

However, W58 rule requires that this permission is enabled. I understand that people often don't care about logs retention (but I could be wrong about that, because having infinite retention period for logs by default will kill your budget), so I am not sure if this issue will be accepted.

Rule code that performs the permissions validation:

https://github.com/stelligent/cfn_nag/blob/8b5f03da74202ba323a145e9d037ddce6cab9dec/lib/cfn-nag/custom_rules/LambdaFunctionCloudWatchLogsRule.rb#L47-L49