aws-powertools / powertools-lambda-typescript

Powertools is a developer toolkit to implement Serverless best practices and increase developer velocity.
https://docs.powertools.aws.dev/lambda/typescript/latest/
MIT No Attribution
1.58k stars 139 forks source link

Bug: dimension value not being validated for empty strings #3302

Open dreamorosi opened 1 week ago

dreamorosi commented 1 week ago

Expected Behavior

When adding a dimension to my metrics, I should get a warning if the dimension value is invalid aka an empty string ("") or undefined/null, and the dimension should not be added to the EMF blobs emitted by the utility.

Current Behavior

Currently the utility doesn't validate the input but only enforces types. In practice this means it's unlikely customers can pass undefined or null unless they're suppressing the warning, but can pass an empty string and generate an EMF blob that will have the invalid dimension.

Code snippet

import { Metrics } from '@aws-lambda-powertools/metrics';

const metrics = new Metrics();

export const handler = async () => {
  metrics.addDimension('FunctionName', '');
  metrics.addMetric('CustomMetric', 'Count', 1);
  metrics.publishStoredMetrics();
};

Steps to Reproduce

  1. Run the code above
  2. Observe that the EMF blob emitted has an empty dimension
  3. Verify that the processed metric in CloudWatch does not include any dimensions

Possible Solution

We should: 1/ validate the input when adding a dimension, 2/ emit a warning if invalid, and 3/ don't add the dimension to the EMF blob

Powertools for AWS Lambda (TypeScript) version

latest

AWS Lambda function runtime

20.x

Packaging format used

npm

Execution logs

{
  "_aws": {
    "Timestamp": 1731086204245,
    "CloudWatchMetrics": [
      {
        "Namespace": "default_namespace",
        "Dimensions": [
          [
            "service",
            "FunctionName"
          ]
        ],
        "Metrics": [
          {
            "Name": "CustomMetric",
            "Unit": "Count"
          }
        ]
      }
    ]
  },
  "service": "service_undefined",
  "FunctionName": "",
  "CustomMetric": 1
}
dreamorosi commented 4 days ago

From the BelieveInServerless Discord server, a customer was having issues while passing a value typed as any which at runtime was a number and that caused the same behavior described above.

Another +1 for runtime validation.

arnabrahman commented 2 days ago

Ok, let's do it 🙂